prettier --write

This commit is contained in:
RainLoop Team 2019-07-04 22:19:24 +03:00
parent 450528ff00
commit 8a0be3212d
164 changed files with 7053 additions and 9008 deletions

View file

@ -1,4 +1,3 @@
import window from 'window'; import window from 'window';
import $ from '$'; import $ from '$';
import _ from '_'; import _ from '_';
@ -7,19 +6,31 @@ import key from 'key';
import ssm from 'ssm'; import ssm from 'ssm';
import { import {
$win, $html, $doc, $win,
startMicrotime, leftPanelDisabled, leftPanelType, $html,
sUserAgent, bMobileDevice, bAnimationSupported $doc,
startMicrotime,
leftPanelDisabled,
leftPanelType,
sUserAgent,
bMobileDevice,
bAnimationSupported
} from 'Common/Globals'; } from 'Common/Globals';
import { import {
noop, isNormal, pString, inArray, microtime, timestamp, noop,
detectDropdownVisibility, windowResizeCallback isNormal,
pString,
inArray,
microtime,
timestamp,
detectDropdownVisibility,
windowResizeCallback
} from 'Common/Utils'; } from 'Common/Utils';
import {KeyState, Magics} from 'Common/Enums'; import { KeyState, Magics } from 'Common/Enums';
import {root, rootAdmin, rootUser, populateAuthSuffix} from 'Common/Links'; import { root, rootAdmin, rootUser, populateAuthSuffix } from 'Common/Links';
import {initOnStartOrLangChange, initNotificationLanguage} from 'Common/Translator'; import { initOnStartOrLangChange, initNotificationLanguage } from 'Common/Translator';
import * as Events from 'Common/Events'; import * as Events from 'Common/Events';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
@ -27,16 +38,14 @@ import LanguageStore from 'Stores/Language';
import ThemeStore from 'Stores/Theme'; import ThemeStore from 'Stores/Theme';
import SocialStore from 'Stores/Social'; import SocialStore from 'Stores/Social';
import {routeOff, setHash} from 'Knoin/Knoin'; import { routeOff, setHash } from 'Knoin/Knoin';
import {AbstractBoot} from 'Knoin/AbstractBoot'; import { AbstractBoot } from 'Knoin/AbstractBoot';
class AbstractApp extends AbstractBoot class AbstractApp extends AbstractBoot {
{
/** /**
* @param {RemoteStorage|AdminRemoteStorage} Remote * @param {RemoteStorage|AdminRemoteStorage} Remote
*/ */
constructor(Remote) constructor(Remote) {
{
super(); super();
this.googlePreviewSupportedCache = null; this.googlePreviewSupportedCache = null;
@ -47,14 +56,15 @@ class AbstractApp extends AbstractBoot
this.iframe = $('<iframe class="internal-hiddden" />').appendTo('body'); this.iframe = $('<iframe class="internal-hiddden" />').appendTo('body');
$win.on('error', (event) => { $win.on('error', (event) => {
if (event && event.originalEvent && event.originalEvent.message && if (
-1 === inArray(event.originalEvent.message, [ event &&
'Script error.', 'Uncaught Error: Error calling method on NPObject.' event.originalEvent &&
])) event.originalEvent.message &&
{ -1 ===
inArray(event.originalEvent.message, ['Script error.', 'Uncaught Error: Error calling method on NPObject.'])
) {
const time = timestamp(); const time = timestamp();
if (this.lastErrorTime >= time) if (this.lastErrorTime >= time) {
{
return; return;
} }
@ -76,19 +86,20 @@ class AbstractApp extends AbstractBoot
Events.pub('window.resize'); Events.pub('window.resize');
}); });
Events.sub('window.resize', _.throttle(() => { Events.sub(
const 'window.resize',
iH = $win.height(), _.throttle(() => {
iW = $win.height(); const iH = $win.height(),
iW = $win.height();
if ($win.__sizes[0] !== iH || $win.__sizes[1] !== iW) if ($win.__sizes[0] !== iH || $win.__sizes[1] !== iW) {
{ $win.__sizes[0] = iH;
$win.__sizes[0] = iH; $win.__sizes[1] = iW;
$win.__sizes[1] = iW;
Events.pub('window.resize.real'); Events.pub('window.resize.real');
} }
}, Magics.Time50ms)); }, Magics.Time50ms)
);
// DEBUG // DEBUG
// Events.sub({ // Events.sub({
@ -100,21 +111,24 @@ class AbstractApp extends AbstractBoot
// } // }
// }); // });
$doc.on('keydown', (event) => { $doc
if (event && event.ctrlKey) .on('keydown', (event) => {
{ if (event && event.ctrlKey) {
$html.addClass('rl-ctrl-key-pressed'); $html.addClass('rl-ctrl-key-pressed');
} }
}).on('keyup', (event) => { })
if (event && !event.ctrlKey) .on('keyup', (event) => {
{ if (event && !event.ctrlKey) {
$html.removeClass('rl-ctrl-key-pressed'); $html.removeClass('rl-ctrl-key-pressed');
} }
}); });
$doc.on('mousemove keypress click', _.debounce(() => { $doc.on(
Events.pub('rl.auto-logout-refresh'); 'mousemove keypress click',
}, Magics.Time5s)); _.debounce(() => {
Events.pub('rl.auto-logout-refresh');
}, Magics.Time5s)
);
key('esc, enter', KeyState.All, () => { key('esc, enter', KeyState.All, () => {
detectDropdownVisibility(); detectDropdownVisibility();
@ -138,17 +152,13 @@ class AbstractApp extends AbstractBoot
* @returns {boolean} * @returns {boolean}
*/ */
download(link) { download(link) {
if (sUserAgent && (-1 < sUserAgent.indexOf('chrome') || -1 < sUserAgent.indexOf('chrome'))) {
if (sUserAgent && (-1 < sUserAgent.indexOf('chrome') || -1 < sUserAgent.indexOf('chrome')))
{
const oLink = window.document.createElement('a'); const oLink = window.document.createElement('a');
oLink.href = link; oLink.href = link;
if (window.document && window.document.createEvent) if (window.document && window.document.createEvent) {
{
const oE = window.document.createEvent.MouseEvents; const oE = window.document.createEvent.MouseEvents;
if (oE && oE.initEvent && oLink.dispatchEvent) if (oE && oE.initEvent && oLink.dispatchEvent) {
{
oE.initEvent('click', true, true); oE.initEvent('click', true, true);
oLink.dispatchEvent(oE); oLink.dispatchEvent(oE);
return true; return true;
@ -156,13 +166,10 @@ class AbstractApp extends AbstractBoot
} }
} }
if (bMobileDevice) if (bMobileDevice) {
{
window.open(link, '_self'); window.open(link, '_self');
window.focus(); window.focus();
} } else {
else
{
this.iframe.attr('src', link); this.iframe.attr('src', link);
// window.document.location.href = link; // window.document.location.href = link;
} }
@ -174,10 +181,9 @@ class AbstractApp extends AbstractBoot
* @returns {boolean} * @returns {boolean}
*/ */
googlePreviewSupported() { googlePreviewSupported() {
if (null === this.googlePreviewSupportedCache) if (null === this.googlePreviewSupportedCache) {
{ this.googlePreviewSupportedCache =
this.googlePreviewSupportedCache = !!Settings.settingsGet('AllowGoogleSocial') && !!Settings.settingsGet('AllowGoogleSocial') && !!Settings.settingsGet('AllowGoogleSocialPreview');
!!Settings.settingsGet('AllowGoogleSocialPreview');
} }
return this.googlePreviewSupportedCache; return this.googlePreviewSupportedCache;
@ -187,9 +193,8 @@ class AbstractApp extends AbstractBoot
* @param {string} title * @param {string} title
*/ */
setWindowTitle(title) { setWindowTitle(title) {
title = ((isNormal(title) && 0 < title.length) ? '' + title : ''); title = isNormal(title) && 0 < title.length ? '' + title : '';
if (Settings.settingsGet('Title')) if (Settings.settingsGet('Title')) {
{
title += (title ? ' - ' : '') + Settings.settingsGet('Title'); title += (title ? ' - ' : '') + Settings.settingsGet('Title');
} }
@ -204,8 +209,7 @@ class AbstractApp extends AbstractBoot
} }
clearClientSideToken() { clearClientSideToken() {
if (window.__rlah_clear) if (window.__rlah_clear) {
{
window.__rlah_clear(); window.__rlah_clear();
} }
} }
@ -214,8 +218,7 @@ class AbstractApp extends AbstractBoot
* @param {string} token * @param {string} token
*/ */
setClientSideToken(token) { setClientSideToken(token) {
if (window.__rlah_set) if (window.__rlah_set) {
{
window.__rlah_set(token); window.__rlah_set(token);
Settings.settingsSet('AuthAccountHash', token); Settings.settingsSet('AuthAccountHash', token);
@ -229,58 +232,42 @@ class AbstractApp extends AbstractBoot
* @param {boolean=} close = false * @param {boolean=} close = false
*/ */
loginAndLogoutReload(admin = false, logout = false, close = false) { loginAndLogoutReload(admin = false, logout = false, close = false) {
const inIframe = !!Settings.appSettingsGet('inIframe'); const inIframe = !!Settings.appSettingsGet('inIframe');
let customLogoutLink = pString(Settings.appSettingsGet('customLogoutLink')); let customLogoutLink = pString(Settings.appSettingsGet('customLogoutLink'));
if (logout) if (logout) {
{
this.clearClientSideToken(); this.clearClientSideToken();
} }
if (logout && close && window.close) if (logout && close && window.close) {
{
window.close(); window.close();
} }
customLogoutLink = customLogoutLink || (admin ? rootAdmin() : rootUser()); customLogoutLink = customLogoutLink || (admin ? rootAdmin() : rootUser());
if (logout && window.location.href !== customLogoutLink) if (logout && window.location.href !== customLogoutLink) {
{
_.delay(() => { _.delay(() => {
if (inIframe && window.parent) {
if (inIframe && window.parent)
{
window.parent.location.href = customLogoutLink; window.parent.location.href = customLogoutLink;
} } else {
else
{
window.location.href = customLogoutLink; window.location.href = customLogoutLink;
} }
$win.trigger('rl.tooltips.diactivate'); $win.trigger('rl.tooltips.diactivate');
}, Magics.Time100ms); }, Magics.Time100ms);
} } else {
else
{
routeOff(); routeOff();
setHash(root(), true); setHash(root(), true);
routeOff(); routeOff();
_.delay(() => { _.delay(() => {
if (inIframe && window.parent) {
if (inIframe && window.parent)
{
window.parent.location.reload(); window.parent.location.reload();
} } else {
else
{
window.location.reload(); window.location.reload();
} }
$win.trigger('rl.tooltips.diactivate'); $win.trigger('rl.tooltips.diactivate');
}, Magics.Time100ms); }, Magics.Time100ms);
} }
} }
@ -290,7 +277,6 @@ class AbstractApp extends AbstractBoot
} }
bootstart() { bootstart() {
// log('Ps' + 'ss, hac' + 'kers! The' + 're\'s not' + 'hing inte' + 'resting :' + ')'); // log('Ps' + 'ss, hac' + 'kers! The' + 're\'s not' + 'hing inte' + 'resting :' + ')');
Events.pub('rl.bootstart'); Events.pub('rl.bootstart');
@ -307,13 +293,10 @@ class AbstractApp extends AbstractBoot
ko.components.register('x-script', require('Component/Script').default); ko.components.register('x-script', require('Component/Script').default);
// ko.components.register('svg-icon', require('Component/SvgIcon').default); // ko.components.register('svg-icon', require('Component/SvgIcon').default);
if (Settings.appSettingsGet('materialDesign') && bAnimationSupported) if (Settings.appSettingsGet('materialDesign') && bAnimationSupported) {
{
ko.components.register('Checkbox', require('Component/MaterialDesign/Checkbox').default); ko.components.register('Checkbox', require('Component/MaterialDesign/Checkbox').default);
ko.components.register('CheckboxSimple', require('Component/Checkbox').default); ko.components.register('CheckboxSimple', require('Component/Checkbox').default);
} } else {
else
{
// ko.components.register('Checkbox', require('Component/Classic/Checkbox').default); // ko.components.register('Checkbox', require('Component/Classic/Checkbox').default);
// ko.components.register('CheckboxSimple', require('Component/Classic/Checkbox').default); // ko.components.register('CheckboxSimple', require('Component/Classic/Checkbox').default);
ko.components.register('Checkbox', require('Component/Checkbox').default); ko.components.register('Checkbox', require('Component/Checkbox').default);
@ -332,8 +315,7 @@ class AbstractApp extends AbstractBoot
leftPanelDisabled(false); leftPanelDisabled(false);
}); });
if (!mobile) if (!mobile) {
{
$html.addClass('rl-desktop'); $html.addClass('rl-desktop');
ssm.addState({ ssm.addState({
@ -381,9 +363,7 @@ class AbstractApp extends AbstractBoot
$html.removeClass('ssm-state-desktop-large'); $html.removeClass('ssm-state-desktop-large');
} }
}); });
} } else {
else
{
$html.addClass('ssm-state-mobile').addClass('rl-mobile'); $html.addClass('ssm-state-mobile').addClass('rl-mobile');
Events.pub('ssm.mobile-enter'); Events.pub('ssm.mobile-enter');
} }
@ -406,4 +386,4 @@ class AbstractApp extends AbstractBoot
} }
} }
export {AbstractApp, AbstractApp as default}; export { AbstractApp, AbstractApp as default };

View file

@ -1,13 +1,12 @@
import window from 'window'; import window from 'window';
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import progressJs from 'progressJs'; import progressJs from 'progressJs';
import {root} from 'Common/Links'; import { root } from 'Common/Links';
import {getNotification} from 'Common/Translator'; import { getNotification } from 'Common/Translator';
import {StorageResultType, Notification} from 'Common/Enums'; import { StorageResultType, Notification } from 'Common/Enums';
import {pInt, isNormal, isArray, inArray, isUnd} from 'Common/Utils'; import { pInt, isNormal, isArray, inArray, isUnd } from 'Common/Utils';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
@ -20,14 +19,13 @@ import PackageStore from 'Stores/Admin/Package';
import CoreStore from 'Stores/Admin/Core'; import CoreStore from 'Stores/Admin/Core';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
import {SettingsAdminScreen} from 'Screen/Admin/Settings'; import { SettingsAdminScreen } from 'Screen/Admin/Settings';
import {LoginAdminScreen} from 'Screen/Admin/Login'; import { LoginAdminScreen } from 'Screen/Admin/Login';
import {hideLoading, routeOff, setHash, startScreens} from 'Knoin/Knoin'; import { hideLoading, routeOff, setHash, startScreens } from 'Knoin/Knoin';
import {AbstractApp} from 'App/Abstract'; import { AbstractApp } from 'App/Abstract';
class AdminApp extends AbstractApp class AdminApp extends AbstractApp {
{
constructor() { constructor() {
super(Remote); super(Remote);
} }
@ -40,14 +38,15 @@ class AdminApp extends AbstractApp
DomainStore.domains.loading(true); DomainStore.domains.loading(true);
Remote.domainList((result, data) => { Remote.domainList((result, data) => {
DomainStore.domains.loading(false); DomainStore.domains.loading(false);
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{ DomainStore.domains(
DomainStore.domains(_.map(data.Result, ([enabled, alias], name) => ({ _.map(data.Result, ([enabled, alias], name) => ({
name: name, name: name,
disabled: ko.observable(!enabled), disabled: ko.observable(!enabled),
alias: alias, alias: alias,
deleteAccess: ko.observable(false) deleteAccess: ko.observable(false)
}))); }))
);
} }
}); });
} }
@ -56,13 +55,14 @@ class AdminApp extends AbstractApp
PluginStore.plugins.loading(true); PluginStore.plugins.loading(true);
Remote.pluginList((result, data) => { Remote.pluginList((result, data) => {
PluginStore.plugins.loading(false); PluginStore.plugins.loading(false);
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{ PluginStore.plugins(
PluginStore.plugins(_.map(data.Result, (item) => ({ _.map(data.Result, (item) => ({
name: item.Name, name: item.Name,
disabled: ko.observable(!item.Enabled), disabled: ko.observable(!item.Enabled),
configured: ko.observable(!!item.Configured) configured: ko.observable(!!item.Configured)
}))); }))
);
} }
}); });
} }
@ -72,8 +72,7 @@ class AdminApp extends AbstractApp
PackageStore.packagesReal(true); PackageStore.packagesReal(true);
Remote.packagesList((result, data) => { Remote.packagesList((result, data) => {
PackageStore.packages.loading(false); PackageStore.packages.loading(false);
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{
PackageStore.packagesReal(!!data.Result.Real); PackageStore.packagesReal(!!data.Result.Real);
PackageStore.packagesMainUpdatable(!!data.Result.MainUpdatable); PackageStore.packagesMainUpdatable(!!data.Result.MainUpdatable);
@ -81,28 +80,25 @@ class AdminApp extends AbstractApp
const loading = {}; const loading = {};
_.each(PackageStore.packages(), (item) => { _.each(PackageStore.packages(), (item) => {
if (item && item.loading()) if (item && item.loading()) {
{
loading[item.file] = item; loading[item.file] = item;
} }
}); });
if (isArray(data.Result.List)) if (isArray(data.Result.List)) {
{ list = _.compact(
list = _.compact(_.map(data.Result.List, (item) => { _.map(data.Result.List, (item) => {
if (item) if (item) {
{ item.loading = ko.observable(!isUnd(loading[item.file]));
item.loading = ko.observable(!isUnd(loading[item.file])); return 'core' === item.type && !item.canBeInstalled ? null : item;
return 'core' === item.type && !item.canBeInstalled ? null : item; }
} return null;
return null; })
})); );
} }
PackageStore.packages(list); PackageStore.packages(list);
} } else {
else
{
PackageStore.packagesReal(false); PackageStore.packagesReal(false);
} }
}); });
@ -116,13 +112,10 @@ class AdminApp extends AbstractApp
CoreStore.coreRemoteVersion(''); CoreStore.coreRemoteVersion('');
CoreStore.coreRemoteRelease(''); CoreStore.coreRemoteRelease('');
CoreStore.coreVersionCompare(-2); CoreStore.coreVersionCompare(-2);
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{
CoreStore.coreReal(true); CoreStore.coreReal(true);
window.location.reload(); window.location.reload();
} } else {
else
{
CoreStore.coreReal(false); CoreStore.coreReal(false);
} }
}); });
@ -133,8 +126,7 @@ class AdminApp extends AbstractApp
CoreStore.coreReal(true); CoreStore.coreReal(true);
Remote.coreData((result, data) => { Remote.coreData((result, data) => {
CoreStore.coreChecking(false); CoreStore.coreChecking(false);
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{
CoreStore.coreReal(!!data.Result.Real); CoreStore.coreReal(!!data.Result.Real);
CoreStore.coreChannel(data.Result.Channel || 'stable'); CoreStore.coreChannel(data.Result.Channel || 'stable');
CoreStore.coreType(data.Result.Type || 'stable'); CoreStore.coreType(data.Result.Type || 'stable');
@ -145,9 +137,7 @@ class AdminApp extends AbstractApp
CoreStore.coreRemoteVersion(data.Result.RemoteVersion || ''); CoreStore.coreRemoteVersion(data.Result.RemoteVersion || '');
CoreStore.coreRemoteRelease(data.Result.RemoteRelease || ''); CoreStore.coreRemoteRelease(data.Result.RemoteRelease || '');
CoreStore.coreVersionCompare(pInt(data.Result.VersionCompare)); CoreStore.coreVersionCompare(pInt(data.Result.VersionCompare));
} } else {
else
{
CoreStore.coreReal(false); CoreStore.coreReal(false);
CoreStore.coreChannel('stable'); CoreStore.coreChannel('stable');
CoreStore.coreType('stable'); CoreStore.coreType('stable');
@ -168,33 +158,25 @@ class AdminApp extends AbstractApp
LicenseStore.licenseError(''); LicenseStore.licenseError('');
Remote.licensing((result, data) => { Remote.licensing((result, data) => {
LicenseStore.licensingProcess(false); LicenseStore.licensingProcess(false);
if (StorageResultType.Success === result && data && data.Result && isNormal(data.Result.Expired)) if (StorageResultType.Success === result && data && data.Result && isNormal(data.Result.Expired)) {
{
LicenseStore.licenseValid(true); LicenseStore.licenseValid(true);
LicenseStore.licenseExpired(pInt(data.Result.Expired)); LicenseStore.licenseExpired(pInt(data.Result.Expired));
LicenseStore.licenseError(''); LicenseStore.licenseError('');
LicenseStore.licensing(true); LicenseStore.licensing(true);
AppStore.prem(true); AppStore.prem(true);
} } else {
else if (
{ data &&
if (data && data.ErrorCode && -1 < inArray(pInt(data.ErrorCode), [ data.ErrorCode &&
Notification.LicensingServerIsUnavailable, -1 < inArray(pInt(data.ErrorCode), [Notification.LicensingServerIsUnavailable, Notification.LicensingExpired])
Notification.LicensingExpired ) {
]))
{
LicenseStore.licenseError(getNotification(pInt(data.ErrorCode))); LicenseStore.licenseError(getNotification(pInt(data.ErrorCode)));
LicenseStore.licensing(true); LicenseStore.licensing(true);
} } else {
else if (StorageResultType.Abort === result) {
{
if (StorageResultType.Abort === result)
{
LicenseStore.licenseError(getNotification(Notification.LicensingServerIsUnavailable)); LicenseStore.licenseError(getNotification(Notification.LicensingServerIsUnavailable));
LicenseStore.licensing(true); LicenseStore.licensing(true);
} } else {
else
{
LicenseStore.licensing(false); LicenseStore.licensing(false);
} }
} }
@ -203,19 +185,16 @@ class AdminApp extends AbstractApp
} }
bootend(bootendCallback = null) { bootend(bootendCallback = null) {
if (progressJs) if (progressJs) {
{
progressJs.end(); progressJs.end();
} }
if (bootendCallback) if (bootendCallback) {
{
bootendCallback(); bootendCallback();
} }
} }
bootstart() { bootstart() {
super.bootstart(); super.bootstart();
AppStore.populate(); AppStore.populate();
@ -223,8 +202,7 @@ class AdminApp extends AbstractApp
hideLoading(); hideLoading();
if (!Settings.appSettingsGet('allowAdminPanel')) if (!Settings.appSettingsGet('allowAdminPanel')) {
{
routeOff(); routeOff();
setHash(root(), true); setHash(root(), true);
routeOff(); routeOff();
@ -232,20 +210,11 @@ class AdminApp extends AbstractApp
_.defer(() => { _.defer(() => {
window.location.href = '/'; window.location.href = '/';
}); });
} } else {
else if (Settings.settingsGet('Auth')) {
{ startScreens([SettingsAdminScreen]);
if (Settings.settingsGet('Auth')) } else {
{ startScreens([LoginAdminScreen]);
startScreens([
SettingsAdminScreen
]);
}
else
{
startScreens([
LoginAdminScreen
]);
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,10 @@
import window from 'window'; import window from 'window';
import {bMobileDevice, bSafari} from 'Common/Globals'; import { bMobileDevice, bSafari } from 'Common/Globals';
import * as Links from 'Common/Links'; import * as Links from 'Common/Links';
import * as Events from 'Common/Events'; import * as Events from 'Common/Events';
import {trim} from 'Common/Utils'; import { trim } from 'Common/Utils';
class Audio class Audio {
{
notificator = null; notificator = null;
player = null; player = null;
@ -20,16 +18,14 @@ class Audio
this.player = this.createNewObject(); this.player = this.createNewObject();
this.supported = !bMobileDevice && !bSafari && !!this.player && !!this.player.play; this.supported = !bMobileDevice && !bSafari && !!this.player && !!this.player.play;
if (this.supported && this.player && this.player.canPlayType) if (this.supported && this.player && this.player.canPlayType) {
{
this.supportedMp3 = '' !== this.player.canPlayType('audio/mpeg;').replace(/no/, ''); this.supportedMp3 = '' !== this.player.canPlayType('audio/mpeg;').replace(/no/, '');
this.supportedWav = '' !== this.player.canPlayType('audio/wav; codecs="1"').replace(/no/, ''); this.supportedWav = '' !== this.player.canPlayType('audio/wav; codecs="1"').replace(/no/, '');
this.supportedOgg = '' !== this.player.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''); this.supportedOgg = '' !== this.player.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, '');
this.supportedNotification = this.supported && this.supportedMp3; this.supportedNotification = this.supported && this.supportedMp3;
} }
if (!this.player || (!this.supportedMp3 && !this.supportedOgg && !this.supportedWav)) if (!this.player || (!this.supportedMp3 && !this.supportedOgg && !this.supportedWav)) {
{
this.supported = false; this.supported = false;
this.supportedMp3 = false; this.supportedMp3 = false;
this.supportedOgg = false; this.supportedOgg = false;
@ -37,8 +33,7 @@ class Audio
this.supportedNotification = false; this.supportedNotification = false;
} }
if (this.supported && this.player) if (this.supported && this.player) {
{
const stopFn = () => this.stop(); const stopFn = () => this.stop();
this.player.addEventListener('ended', stopFn); this.player.addEventListener('ended', stopFn);
@ -50,8 +45,7 @@ class Audio
createNewObject() { createNewObject() {
const player = window.Audio ? new window.Audio() : null; const player = window.Audio ? new window.Audio() : null;
if (player && player.canPlayType && player.pause && player.play) if (player && player.canPlayType && player.pause && player.play) {
{
player.preload = 'none'; player.preload = 'none';
player.loop = false; player.loop = false;
player.autoplay = false; player.autoplay = false;
@ -66,8 +60,7 @@ class Audio
} }
stop() { stop() {
if (this.supported && this.player.pause) if (this.supported && this.player.pause) {
{
this.player.pause(); this.player.pause();
} }
@ -79,10 +72,8 @@ class Audio
} }
clearName(name = '', ext = '') { clearName(name = '', ext = '') {
name = trim(name); name = trim(name);
if (ext && '.' + ext === name.toLowerCase().substr((ext.length + 1) * -1)) if (ext && '.' + ext === name.toLowerCase().substr((ext.length + 1) * -1)) {
{
name = trim(name.substr(0, name.length - 4)); name = trim(name.substr(0, name.length - 4));
} }
@ -90,8 +81,7 @@ class Audio
} }
playMp3(url, name) { playMp3(url, name) {
if (this.supported && this.supportedMp3) if (this.supported && this.supportedMp3) {
{
this.player.src = url; this.player.src = url;
this.player.play(); this.player.play();
@ -100,8 +90,7 @@ class Audio
} }
playOgg(url, name) { playOgg(url, name) {
if (this.supported && this.supportedOgg) if (this.supported && this.supportedOgg) {
{
this.player.src = url; this.player.src = url;
this.player.play(); this.player.play();
@ -113,8 +102,7 @@ class Audio
} }
playWav(url, name) { playWav(url, name) {
if (this.supported && this.supportedWav) if (this.supported && this.supportedWav) {
{
this.player.src = url; this.player.src = url;
this.player.play(); this.player.play();
@ -123,16 +111,13 @@ class Audio
} }
playNotification() { playNotification() {
if (this.supported && this.supportedMp3) if (this.supported && this.supportedMp3) {
{ if (!this.notificator) {
if (!this.notificator)
{
this.notificator = this.createNewObject(); this.notificator = this.createNewObject();
this.notificator.src = Links.sound('new-mail.mp3'); this.notificator.src = Links.sound('new-mail.mp3');
} }
if (this.notificator && this.notificator.play) if (this.notificator && this.notificator.play) {
{
this.notificator.play(); this.notificator.play();
} }
} }

View file

@ -1,4 +1,3 @@
// Base64 encode / decode // Base64 encode / decode
// http://www.webtoolkit.info/ // http://www.webtoolkit.info/
@ -6,23 +5,28 @@ const BASE_64_CHR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456
/* eslint-disable */ /* eslint-disable */
const Base64 = { const Base64 = {
// public method for urlsafe encoding // public method for urlsafe encoding
urlsafe_encode: (input) => Base64.encode(input) urlsafe_encode: (input) =>
.replace(/[+]/g, '-').replace(/[\/]/g, '_').replace(/[=]/g, ''), Base64.encode(input)
.replace(/[+]/g, '-')
.replace(/[\/]/g, '_')
.replace(/[=]/g, ''),
// public method for encoding // public method for encoding
encode: (input) => { encode: (input) => {
let output = '',
let chr1,
output = '', chr2,
chr1, chr2, chr3, enc1, enc2, enc3, enc4, chr3,
enc1,
enc2,
enc3,
enc4,
i = 0; i = 0;
input = Base64._utf8_encode(input); input = Base64._utf8_encode(input);
while (i < input.length) while (i < input.length) {
{
chr1 = input.charCodeAt(i++); chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++);
@ -32,18 +36,18 @@ const Base64 = {
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63; enc4 = chr3 & 63;
if (isNaN(chr2)) if (isNaN(chr2)) {
{
enc3 = enc4 = 64; enc3 = enc4 = 64;
} } else if (isNaN(chr3)) {
else if (isNaN(chr3))
{
enc4 = 64; enc4 = 64;
} }
output = output + output =
BASE_64_CHR.charAt(enc1) + BASE_64_CHR.charAt(enc2) + output +
BASE_64_CHR.charAt(enc3) + BASE_64_CHR.charAt(enc4); BASE_64_CHR.charAt(enc1) +
BASE_64_CHR.charAt(enc2) +
BASE_64_CHR.charAt(enc3) +
BASE_64_CHR.charAt(enc4);
} }
return output; return output;
@ -51,16 +55,19 @@ const Base64 = {
// public method for decoding // public method for decoding
decode: (input) => { decode: (input) => {
let output = '',
let chr1,
output = '', chr2,
chr1, chr2, chr3, enc1, enc2, enc3, enc4, chr3,
enc1,
enc2,
enc3,
enc4,
i = 0; i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
while (i < input.length) while (i < input.length) {
{
enc1 = BASE_64_CHR.indexOf(input.charAt(i++)); enc1 = BASE_64_CHR.indexOf(input.charAt(i++));
enc2 = BASE_64_CHR.indexOf(input.charAt(i++)); enc2 = BASE_64_CHR.indexOf(input.charAt(i++));
enc3 = BASE_64_CHR.indexOf(input.charAt(i++)); enc3 = BASE_64_CHR.indexOf(input.charAt(i++));
@ -72,13 +79,11 @@ const Base64 = {
output = output + String.fromCharCode(chr1); output = output + String.fromCharCode(chr1);
if (enc3 !== 64) if (enc3 !== 64) {
{
output = output + String.fromCharCode(chr2); output = output + String.fromCharCode(chr2);
} }
if (enc4 !== 64) if (enc4 !== 64) {
{
output = output + String.fromCharCode(chr3); output = output + String.fromCharCode(chr3);
} }
} }
@ -88,30 +93,22 @@ const Base64 = {
// private method for UTF-8 encoding // private method for UTF-8 encoding
_utf8_encode: (string) => { _utf8_encode: (string) => {
string = string.replace(/\r\n/g, '\n');
string = string.replace(/\r\n/g, "\n"); let utftext = '',
let
utftext = '',
n = 0, n = 0,
l = string.length, l = string.length,
c = 0; c = 0;
for (; n < l; n++) { for (; n < l; n++) {
c = string.charCodeAt(n); c = string.charCodeAt(n);
if (c < 128) if (c < 128) {
{
utftext += String.fromCharCode(c); utftext += String.fromCharCode(c);
} } else if (c > 127 && c < 2048) {
else if ((c > 127) && (c < 2048))
{
utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128); utftext += String.fromCharCode((c & 63) | 128);
} } else {
else
{
utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128); utftext += String.fromCharCode((c & 63) | 128);
@ -123,33 +120,25 @@ const Base64 = {
// private method for UTF-8 decoding // private method for UTF-8 decoding
_utf8_decode: (utftext) => { _utf8_decode: (utftext) => {
let string = '',
let
string = '',
i = 0, i = 0,
c = 0, c = 0,
c2 = 0, c2 = 0,
c3 = 0; c3 = 0;
while ( i < utftext.length ) while (i < utftext.length) {
{
c = utftext.charCodeAt(i); c = utftext.charCodeAt(i);
if (c < 128) if (c < 128) {
{
string += String.fromCharCode(c); string += String.fromCharCode(c);
i++; i++;
} } else if (c > 191 && c < 224) {
else if((c > 191) && (c < 224)) c2 = utftext.charCodeAt(i + 1);
{
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2; i += 2;
} } else {
else c2 = utftext.charCodeAt(i + 1);
{ c3 = utftext.charCodeAt(i + 2);
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3; i += 3;
} }

View file

@ -1,9 +1,8 @@
import window from 'window'; import window from 'window';
import progressJs from 'progressJs'; import progressJs from 'progressJs';
import {jassl} from 'Common/Jassl'; import { jassl } from 'Common/Jassl';
import {getHash, setHash, clearHash} from 'Storage/RainLoop'; import { getHash, setHash, clearHash } from 'Storage/RainLoop';
let RL_APP_DATA_STORAGE = null; let RL_APP_DATA_STORAGE = null;
@ -14,38 +13,38 @@ window.__rlah_clear = () => clearHash();
window.__rlah_data = () => RL_APP_DATA_STORAGE; window.__rlah_data = () => RL_APP_DATA_STORAGE;
const useJsNextBundle = (function() { const useJsNextBundle = (function() {
// try { // try {
// //
// (function() { // (function() {
// eval(` // eval(`
// // let + const // // let + const
//const x = 5; let y = 4; var z = 4; //const x = 5; let y = 4; var z = 4;
// //
// // Arrow Function // // Arrow Function
//const f = () => 'rainloop'; //const f = () => 'rainloop';
// //
// // Default + Rest + Spread // // Default + Rest + Spread
//const d = (test = 1, ...t) => 'rainloop'; //const d = (test = 1, ...t) => 'rainloop';
//d(...[1, 2, 3]); //d(...[1, 2, 3]);
// //
//// Destructuring //// Destructuring
//let [a, b] = [1, 2]; //let [a, b] = [1, 2];
//({a, b} = {a: 1, b: 2}); //({a, b} = {a: 1, b: 2});
// //
//// Class //// Class
//class Q1 { constructor() {} } //class Q1 { constructor() {} }
// //
//// Class extends + super //// Class extends + super
//class Q2 extends Q1 { constructor() { super() } } //class Q2 extends Q1 { constructor() { super() } }
// //
//`); //`);
// }()); // }());
// //
// return true; // return true;
// } // }
// catch (e) {} // catch (e) {}
return false; return false;
}()); })();
/* eslint-enable */ /* eslint-enable */
/** /**
@ -53,19 +52,20 @@ const useJsNextBundle = (function() {
* @param {string} name * @param {string} name
* @returns {string} * @returns {string}
*/ */
function getComputedStyle(id, name) function getComputedStyle(id, name) {
{
const element = window.document.getElementById(id); const element = window.document.getElementById(id);
return element && element.currentStyle ? element.currentStyle[name] : return element && element.currentStyle
(window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null); ? element.currentStyle[name]
: window.getComputedStyle
? window.getComputedStyle(element, null).getPropertyValue(name)
: null;
} }
/** /**
* @param {string} styles * @param {string} styles
* @returns {void} * @returns {void}
*/ */
function includeStyle(styles) function includeStyle(styles) {
{
window.document.write(unescape('%3Csty' + 'le%3E' + styles + '"%3E%3C/' + 'sty' + 'le%3E')); // eslint-disable-line no-useless-concat window.document.write(unescape('%3Csty' + 'le%3E' + styles + '"%3E%3C/' + 'sty' + 'le%3E')); // eslint-disable-line no-useless-concat
} }
@ -73,22 +73,31 @@ function includeStyle(styles)
* @param {string} src * @param {string} src
* @returns {void} * @returns {void}
*/ */
function includeScr(src) function includeScr(src) {
{ window.document.write(
window.document.write(unescape('%3Csc' + 'ript type="text/jav' + 'ascr' + 'ipt" data-cfasync="false" sr' + 'c="' + src + '"%3E%3C/' + 'scr' + 'ipt%3E')); // eslint-disable-line no-useless-concat unescape(
'%3Csc' +
'ript type="text/jav' +
'ascr' +
'ipt" data-cfasync="false" sr' +
'c="' +
src +
'"%3E%3C/' +
'scr' +
'ipt%3E'
)
); // eslint-disable-line no-useless-concat
} }
/** /**
* @returns {boolean} * @returns {boolean}
*/ */
function includeLayout() function includeLayout() {
{
const app = window.document.getElementById('rl-app'); const app = window.document.getElementById('rl-app');
require('Styles/@Boot.css'); require('Styles/@Boot.css');
if (app) if (app) {
{
const layout = require('Html/Layout.html'); const layout = require('Html/Layout.html');
app.innerHTML = ((layout && layout.default ? layout.default : layout) || '').replace(/[\r\n\t]+/g, ''); app.innerHTML = ((layout && layout.default ? layout.default : layout) || '').replace(/[\r\n\t]+/g, '');
return true; return true;
@ -103,8 +112,7 @@ function includeLayout()
* @param {boolean} mobileDevice = false * @param {boolean} mobileDevice = false
* @returns {void} * @returns {void}
*/ */
function includeAppScr({admin = false, mobile = false, mobileDevice = false}) function includeAppScr({ admin = false, mobile = false, mobileDevice = false }) {
{
let src = './?/'; let src = './?/';
src += admin ? 'Admin' : ''; src += admin ? 'Admin' : '';
src += 'AppData@'; src += 'AppData@';
@ -112,19 +120,25 @@ function includeAppScr({admin = false, mobile = false, mobileDevice = false})
src += mobileDevice ? '-1' : '-0'; src += mobileDevice ? '-1' : '-0';
src += '/'; src += '/';
includeScr(src + (window.__rlah ? window.__rlah() || '0' : '0') + '/' + window.Math.random().toString().substr(2) + '/'); includeScr(
src +
(window.__rlah ? window.__rlah() || '0' : '0') +
'/' +
window.Math.random()
.toString()
.substr(2) +
'/'
);
} }
/** /**
* @returns {object} * @returns {object}
*/ */
function getRainloopBootData() function getRainloopBootData() {
{
let result = {}; let result = {};
const meta = window.document.getElementById('app-boot-data'); const meta = window.document.getElementById('app-boot-data');
if (meta && meta.getAttribute) if (meta && meta.getAttribute) {
{
result = JSON.parse(meta.getAttribute('content')) || {}; result = JSON.parse(meta.getAttribute('content')) || {};
} }
@ -135,31 +149,25 @@ function getRainloopBootData()
* @param {string} additionalError * @param {string} additionalError
* @returns {void} * @returns {void}
*/ */
function showError(additionalError) function showError(additionalError) {
{ const oR = window.document.getElementById('rl-loading'),
const
oR = window.document.getElementById('rl-loading'),
oL = window.document.getElementById('rl-loading-error'), oL = window.document.getElementById('rl-loading-error'),
oLA = window.document.getElementById('rl-loading-error-additional'); oLA = window.document.getElementById('rl-loading-error-additional');
if (oR) if (oR) {
{
oR.style.display = 'none'; oR.style.display = 'none';
} }
if (oL) if (oL) {
{
oL.style.display = 'block'; oL.style.display = 'block';
} }
if (oLA && additionalError) if (oLA && additionalError) {
{
oLA.style.display = 'block'; oLA.style.display = 'block';
oLA.innerHTML = additionalError; oLA.innerHTML = additionalError;
} }
if (progressJs) if (progressJs) {
{
progressJs.set(100).end(); progressJs.set(100).end();
} }
} }
@ -168,19 +176,15 @@ function showError(additionalError)
* @param {string} description * @param {string} description
* @returns {void} * @returns {void}
*/ */
function showDescriptionAndLoading(description) function showDescriptionAndLoading(description) {
{ const oE = window.document.getElementById('rl-loading'),
const
oE = window.document.getElementById('rl-loading'),
oElDesc = window.document.getElementById('rl-loading-desc'); oElDesc = window.document.getElementById('rl-loading-desc');
if (oElDesc && description) if (oElDesc && description) {
{
oElDesc.innerHTML = description; oElDesc.innerHTML = description;
} }
if (oE && oE.style) if (oE && oE.style) {
{
oE.style.opacity = 0; oE.style.opacity = 0;
window.setTimeout(() => { window.setTimeout(() => {
oE.style.opacity = 1; oE.style.opacity = 1;
@ -193,16 +197,12 @@ function showDescriptionAndLoading(description)
* @param {string} additionalError * @param {string} additionalError
* @returns {void} * @returns {void}
*/ */
function runMainBoot(withError, additionalError) function runMainBoot(withError, additionalError) {
{ if (window.__APP_BOOT && !withError) {
if (window.__APP_BOOT && !withError)
{
window.__APP_BOOT(() => { window.__APP_BOOT(() => {
showError(additionalError); showError(additionalError);
}); });
} } else {
else
{
showError(additionalError); showError(additionalError);
} }
} }
@ -210,43 +210,47 @@ function runMainBoot(withError, additionalError)
/** /**
* @returns {void} * @returns {void}
*/ */
function runApp() function runApp() {
{
const appData = window.__rlah_data(); const appData = window.__rlah_data();
if (jassl && progressJs && appData && appData.TemplatesLink && appData.LangLink && if (
appData.StaticLibJsLink && appData.StaticAppJsLink && appData.StaticAppJsNextLink && appData.StaticEditorJsLink) jassl &&
{ progressJs &&
appData &&
appData.TemplatesLink &&
appData.LangLink &&
appData.StaticLibJsLink &&
appData.StaticAppJsLink &&
appData.StaticAppJsNextLink &&
appData.StaticEditorJsLink
) {
const p = progressJs; const p = progressJs;
p.setOptions({theme: 'rainloop'}); p.setOptions({ theme: 'rainloop' });
p.start().set(5); p.start().set(5);
const libs = () => jassl(appData.StaticLibJsLink).then(() => { const libs = () =>
if (window.$) jassl(appData.StaticLibJsLink).then(() => {
{ if (window.$) {
window.$('#rl-check').remove(); window.$('#rl-check').remove();
if (appData.IncludeBackground) if (appData.IncludeBackground) {
{ window
window.$('#rl-bg') .$('#rl-bg')
.attr('style', 'background-image: none !important;') .attr('style', 'background-image: none !important;')
.backstretch( .backstretch(
appData.IncludeBackground.replace('{{USER}}', (window.__rlah ? (window.__rlah() || '0') : '0')), appData.IncludeBackground.replace('{{USER}}', window.__rlah ? window.__rlah() || '0' : '0'),
{fade: 100, centeredX: true, centeredY: true} { fade: 100, centeredX: true, centeredY: true }
) )
.removeAttr('style'); .removeAttr('style');
}
} }
} });
});
libs() libs()
.then(() => { .then(() => {
p.set(20); p.set(20);
return window.Promise.all([ return window.Promise.all([jassl(appData.TemplatesLink), jassl(appData.LangLink)]);
jassl(appData.TemplatesLink),
jassl(appData.LangLink)
]);
}) })
.then(() => { .then(() => {
p.set(30); p.set(30);
@ -271,9 +275,7 @@ function runApp()
window.__initEditor = null; window.__initEditor = null;
} }
}); });
} } else {
else
{
runMainBoot(true); runMainBoot(true);
} }
} }
@ -283,20 +285,16 @@ function runApp()
* @returns {void} * @returns {void}
*/ */
window.__initAppData = function(data) { window.__initAppData = function(data) {
RL_APP_DATA_STORAGE = data; RL_APP_DATA_STORAGE = data;
window.__rlah_set(); window.__rlah_set();
if (RL_APP_DATA_STORAGE) if (RL_APP_DATA_STORAGE) {
{ if (RL_APP_DATA_STORAGE.NewThemeLink) {
if (RL_APP_DATA_STORAGE.NewThemeLink)
{
(window.document.getElementById('app-theme-link') || {}).href = RL_APP_DATA_STORAGE.NewThemeLink; (window.document.getElementById('app-theme-link') || {}).href = RL_APP_DATA_STORAGE.NewThemeLink;
} }
if (RL_APP_DATA_STORAGE.IncludeCss) if (RL_APP_DATA_STORAGE.IncludeCss) {
{
includeStyle(RL_APP_DATA_STORAGE.IncludeCss); includeStyle(RL_APP_DATA_STORAGE.IncludeCss);
} }
@ -310,26 +308,20 @@ window.__initAppData = function(data) {
* @returns {void} * @returns {void}
*/ */
window.__runBoot = function() { window.__runBoot = function() {
if (!window.navigator || !window.navigator.cookieEnabled) {
if (!window.navigator || !window.navigator.cookieEnabled)
{
window.document.location.replace('./?/NoCookie'); window.document.location.replace('./?/NoCookie');
} }
const root = window.document.documentElement; const root = window.document.documentElement;
if ('none' !== getComputedStyle('rl-check', 'display')) if ('none' !== getComputedStyle('rl-check', 'display')) {
{
root.className += ' no-css'; root.className += ' no-css';
} }
if (useJsNextBundle) if (useJsNextBundle) {
{
root.className += ' js-next'; root.className += ' js-next';
} }
if (includeLayout()) if (includeLayout()) {
{
includeAppScr(getRainloopBootData()); includeAppScr(getRainloopBootData());
} }
}; };

View file

@ -1,7 +1,6 @@
import _ from '_'; import _ from '_';
import {Capa, MessageSetAction} from 'Common/Enums'; import { Capa, MessageSetAction } from 'Common/Enums';
import {trim, pInt, isArray} from 'Common/Utils'; import { trim, pInt, isArray } from 'Common/Utils';
import * as Links from 'Common/Links'; import * as Links from 'Common/Links';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
@ -19,8 +18,7 @@ const REQUESTED_MESSAGE_CACHE = {},
/** /**
* @returns {void} * @returns {void}
*/ */
export function clear() export function clear() {
{
FOLDERS_CACHE = {}; FOLDERS_CACHE = {};
FOLDERS_NAME_CACHE = {}; FOLDERS_NAME_CACHE = {};
FOLDERS_HASH_CACHE = {}; FOLDERS_HASH_CACHE = {};
@ -33,8 +31,7 @@ export function clear()
* @param {Function} callback * @param {Function} callback
* @returns {string} * @returns {string}
*/ */
export function getUserPic(email, callback) export function getUserPic(email, callback) {
{
email = trim(email); email = trim(email);
callback(capaGravatar && '' !== email ? Links.avatarLink(email) : '', email); callback(capaGravatar && '' !== email ? Links.avatarLink(email) : '', email);
} }
@ -44,8 +41,7 @@ export function getUserPic(email, callback)
* @param {string} uid * @param {string} uid
* @returns {string} * @returns {string}
*/ */
export function getMessageKey(folderFullNameRaw, uid) export function getMessageKey(folderFullNameRaw, uid) {
{
return `${folderFullNameRaw}#${uid}`; return `${folderFullNameRaw}#${uid}`;
} }
@ -53,8 +49,7 @@ export function getMessageKey(folderFullNameRaw, uid)
* @param {string} folder * @param {string} folder
* @param {string} uid * @param {string} uid
*/ */
export function addRequestedMessage(folder, uid) export function addRequestedMessage(folder, uid) {
{
REQUESTED_MESSAGE_CACHE[getMessageKey(folder, uid)] = true; REQUESTED_MESSAGE_CACHE[getMessageKey(folder, uid)] = true;
} }
@ -63,8 +58,7 @@ export function addRequestedMessage(folder, uid)
* @param {string} uid * @param {string} uid
* @returns {boolean} * @returns {boolean}
*/ */
export function hasRequestedMessage(folder, uid) export function hasRequestedMessage(folder, uid) {
{
return true === REQUESTED_MESSAGE_CACHE[getMessageKey(folder, uid)]; return true === REQUESTED_MESSAGE_CACHE[getMessageKey(folder, uid)];
} }
@ -72,8 +66,7 @@ export function hasRequestedMessage(folder, uid)
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {string} uid * @param {string} uid
*/ */
export function addNewMessageCache(folderFullNameRaw, uid) export function addNewMessageCache(folderFullNameRaw, uid) {
{
NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)] = true; NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)] = true;
} }
@ -81,10 +74,8 @@ export function addNewMessageCache(folderFullNameRaw, uid)
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {string} uid * @param {string} uid
*/ */
export function hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid) export function hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid) {
{ if (NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)]) {
if (NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)])
{
NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)] = null; NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)] = null;
return true; return true;
} }
@ -94,16 +85,14 @@ export function hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid)
/** /**
* @returns {void} * @returns {void}
*/ */
export function clearNewMessageCache() export function clearNewMessageCache() {
{
NEW_MESSAGE_CACHE = {}; NEW_MESSAGE_CACHE = {};
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function getFolderInboxName() export function getFolderInboxName() {
{
return '' === inboxFolderName ? 'INBOX' : inboxFolderName; return '' === inboxFolderName ? 'INBOX' : inboxFolderName;
} }
@ -111,8 +100,7 @@ export function getFolderInboxName()
* @param {string} folderHash * @param {string} folderHash
* @returns {string} * @returns {string}
*/ */
export function getFolderFullNameRaw(folderHash) export function getFolderFullNameRaw(folderHash) {
{
return '' !== folderHash && FOLDERS_NAME_CACHE[folderHash] ? FOLDERS_NAME_CACHE[folderHash] : ''; return '' !== folderHash && FOLDERS_NAME_CACHE[folderHash] ? FOLDERS_NAME_CACHE[folderHash] : '';
} }
@ -120,11 +108,9 @@ export function getFolderFullNameRaw(folderHash)
* @param {string} folderHash * @param {string} folderHash
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
*/ */
export function setFolderFullNameRaw(folderHash, folderFullNameRaw) export function setFolderFullNameRaw(folderHash, folderFullNameRaw) {
{
FOLDERS_NAME_CACHE[folderHash] = folderFullNameRaw; FOLDERS_NAME_CACHE[folderHash] = folderFullNameRaw;
if ('INBOX' === folderFullNameRaw || '' === inboxFolderName) if ('INBOX' === folderFullNameRaw || '' === inboxFolderName) {
{
inboxFolderName = folderFullNameRaw; inboxFolderName = folderFullNameRaw;
} }
} }
@ -133,8 +119,7 @@ export function setFolderFullNameRaw(folderHash, folderFullNameRaw)
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @returns {string} * @returns {string}
*/ */
export function getFolderHash(folderFullNameRaw) export function getFolderHash(folderFullNameRaw) {
{
return '' !== folderFullNameRaw && FOLDERS_HASH_CACHE[folderFullNameRaw] ? FOLDERS_HASH_CACHE[folderFullNameRaw] : ''; return '' !== folderFullNameRaw && FOLDERS_HASH_CACHE[folderFullNameRaw] ? FOLDERS_HASH_CACHE[folderFullNameRaw] : '';
} }
@ -142,10 +127,8 @@ export function getFolderHash(folderFullNameRaw)
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {string} folderHash * @param {string} folderHash
*/ */
export function setFolderHash(folderFullNameRaw, folderHash) export function setFolderHash(folderFullNameRaw, folderHash) {
{ if ('' !== folderFullNameRaw) {
if ('' !== folderFullNameRaw)
{
FOLDERS_HASH_CACHE[folderFullNameRaw] = folderHash; FOLDERS_HASH_CACHE[folderFullNameRaw] = folderHash;
} }
} }
@ -154,17 +137,17 @@ export function setFolderHash(folderFullNameRaw, folderHash)
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @returns {string} * @returns {string}
*/ */
export function getFolderUidNext(folderFullNameRaw) export function getFolderUidNext(folderFullNameRaw) {
{ return '' !== folderFullNameRaw && FOLDERS_UID_NEXT_CACHE[folderFullNameRaw]
return '' !== folderFullNameRaw && FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] ? FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] : ''; ? FOLDERS_UID_NEXT_CACHE[folderFullNameRaw]
: '';
} }
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {string} uidNext * @param {string} uidNext
*/ */
export function setFolderUidNext(folderFullNameRaw, uidNext) export function setFolderUidNext(folderFullNameRaw, uidNext) {
{
FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] = uidNext; FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] = uidNext;
} }
@ -172,8 +155,7 @@ export function setFolderUidNext(folderFullNameRaw, uidNext)
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @returns {?FolderModel} * @returns {?FolderModel}
*/ */
export function getFolderFromCacheList(folderFullNameRaw) export function getFolderFromCacheList(folderFullNameRaw) {
{
return '' !== folderFullNameRaw && FOLDERS_CACHE[folderFullNameRaw] ? FOLDERS_CACHE[folderFullNameRaw] : null; return '' !== folderFullNameRaw && FOLDERS_CACHE[folderFullNameRaw] ? FOLDERS_CACHE[folderFullNameRaw] : null;
} }
@ -181,16 +163,14 @@ export function getFolderFromCacheList(folderFullNameRaw)
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {?FolderModel} folder * @param {?FolderModel} folder
*/ */
export function setFolderToCacheList(folderFullNameRaw, folder) export function setFolderToCacheList(folderFullNameRaw, folder) {
{
FOLDERS_CACHE[folderFullNameRaw] = folder; FOLDERS_CACHE[folderFullNameRaw] = folder;
} }
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
*/ */
export function removeFolderFromCacheList(folderFullNameRaw) export function removeFolderFromCacheList(folderFullNameRaw) {
{
setFolderToCacheList(folderFullNameRaw, null); setFolderToCacheList(folderFullNameRaw, null);
} }
@ -199,10 +179,10 @@ export function removeFolderFromCacheList(folderFullNameRaw)
* @param {string} uid * @param {string} uid
* @returns {?Array} * @returns {?Array}
*/ */
export function getMessageFlagsFromCache(folderFullName, uid) export function getMessageFlagsFromCache(folderFullName, uid) {
{ return MESSAGE_FLAGS_CACHE[folderFullName] && MESSAGE_FLAGS_CACHE[folderFullName][uid]
return MESSAGE_FLAGS_CACHE[folderFullName] && MESSAGE_FLAGS_CACHE[folderFullName][uid] ? ? MESSAGE_FLAGS_CACHE[folderFullName][uid]
MESSAGE_FLAGS_CACHE[folderFullName][uid] : null; : null;
} }
/** /**
@ -210,10 +190,8 @@ export function getMessageFlagsFromCache(folderFullName, uid)
* @param {string} uid * @param {string} uid
* @param {Array} flagsCache * @param {Array} flagsCache
*/ */
export function setMessageFlagsToCache(folderFullName, uid, flagsCache) export function setMessageFlagsToCache(folderFullName, uid, flagsCache) {
{ if (!MESSAGE_FLAGS_CACHE[folderFullName]) {
if (!MESSAGE_FLAGS_CACHE[folderFullName])
{
MESSAGE_FLAGS_CACHE[folderFullName] = {}; MESSAGE_FLAGS_CACHE[folderFullName] = {};
} }
@ -223,29 +201,22 @@ export function setMessageFlagsToCache(folderFullName, uid, flagsCache)
/** /**
* @param {string} folderFullName * @param {string} folderFullName
*/ */
export function clearMessageFlagsFromCacheByFolder(folderFullName) export function clearMessageFlagsFromCacheByFolder(folderFullName) {
{
MESSAGE_FLAGS_CACHE[folderFullName] = {}; MESSAGE_FLAGS_CACHE[folderFullName] = {};
} }
/** /**
* @param {(MessageModel|null)} message * @param {(MessageModel|null)} message
*/ */
export function initMessageFlagsFromCache(message) export function initMessageFlagsFromCache(message) {
{ if (message) {
const uid = message.uid,
if (message)
{
const
uid = message.uid,
flags = getMessageFlagsFromCache(message.folderFullNameRaw, uid); flags = getMessageFlagsFromCache(message.folderFullNameRaw, uid);
if (flags && 0 < flags.length) if (flags && 0 < flags.length) {
{
message.flagged(!!flags[1]); message.flagged(!!flags[1]);
if (!message.isSimpleMessage) if (!message.isSimpleMessage) {
{
message.unseen(!!flags[0]); message.unseen(!!flags[0]);
message.answered(!!flags[2]); message.answered(!!flags[2]);
message.forwarded(!!flags[3]); message.forwarded(!!flags[3]);
@ -254,8 +225,7 @@ export function initMessageFlagsFromCache(message)
} }
} }
if (0 < message.threads().length) if (0 < message.threads().length) {
{
const unseenSubUid = _.find(message.threads(), (sSubUid) => { const unseenSubUid = _.find(message.threads(), (sSubUid) => {
if (uid !== sSubUid) { if (uid !== sSubUid) {
const subFlags = getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid); const subFlags = getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid);
@ -281,15 +251,16 @@ export function initMessageFlagsFromCache(message)
/** /**
* @param {(MessageModel|null)} message * @param {(MessageModel|null)} message
*/ */
export function storeMessageFlagsToCache(message) export function storeMessageFlagsToCache(message) {
{ if (message) {
if (message) setMessageFlagsToCache(message.folderFullNameRaw, message.uid, [
{ message.unseen(),
setMessageFlagsToCache( message.flagged(),
message.folderFullNameRaw, message.uid, message.answered(),
[message.unseen(), message.flagged(), message.answered(), message.forwarded(), message.forwarded(),
message.isReadReceipt(), message.deletedMark()] message.isReadReceipt(),
); message.deletedMark()
]);
} }
} }
@ -298,10 +269,8 @@ export function storeMessageFlagsToCache(message)
* @param {string} uid * @param {string} uid
* @param {Array} flags * @param {Array} flags
*/ */
export function storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags) export function storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags) {
{ if (isArray(flags) && 0 < flags.length) {
if (isArray(flags) && 0 < flags.length)
{
setMessageFlagsToCache(folder, uid, flags); setMessageFlagsToCache(folder, uid, flags);
} }
} }
@ -311,21 +280,16 @@ export function storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags)
* @param {string} uid * @param {string} uid
* @param {number} setAction * @param {number} setAction
*/ */
export function storeMessageFlagsToCacheBySetAction(folder, uid, setAction) export function storeMessageFlagsToCacheBySetAction(folder, uid, setAction) {
{
let unread = 0; let unread = 0;
const flags = getMessageFlagsFromCache(folder, uid); const flags = getMessageFlagsFromCache(folder, uid);
if (isArray(flags) && 0 < flags.length) if (isArray(flags) && 0 < flags.length) {
{ if (flags[0]) {
if (flags[0])
{
unread = 1; unread = 1;
} }
switch (setAction) switch (setAction) {
{
case MessageSetAction.SetSeen: case MessageSetAction.SetSeen:
flags[0] = false; flags[0] = false;
break; break;

View file

@ -1,39 +1,31 @@
import window from 'window'; import window from 'window';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import {isUnd} from 'Common/Utils'; import { isUnd } from 'Common/Utils';
import {CLIENT_SIDE_STORAGE_INDEX_NAME} from 'Common/Consts'; import { CLIENT_SIDE_STORAGE_INDEX_NAME } from 'Common/Consts';
class CookieDriver class CookieDriver {
{
/** /**
* @param {string} key * @param {string} key
* @param {*} data * @param {*} data
* @returns {boolean} * @returns {boolean}
*/ */
set(key, data) { set(key, data) {
let result = false,
let
result = false,
storageResult = null; storageResult = null;
try try {
{
storageResult = Cookies.getJSON(CLIENT_SIDE_STORAGE_INDEX_NAME); storageResult = Cookies.getJSON(CLIENT_SIDE_STORAGE_INDEX_NAME);
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
(storageResult || (storageResult = {}))[key] = data; (storageResult || (storageResult = {}))[key] = data;
try try {
{
Cookies.set(CLIENT_SIDE_STORAGE_INDEX_NAME, storageResult, { Cookies.set(CLIENT_SIDE_STORAGE_INDEX_NAME, storageResult, {
expires: 30 expires: 30
}); });
result = true; result = true;
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
return result; return result;
} }
@ -43,15 +35,12 @@ class CookieDriver
* @returns {*} * @returns {*}
*/ */
get(key) { get(key) {
let result = null; let result = null;
try try {
{
const storageResult = Cookies.getJSON(CLIENT_SIDE_STORAGE_INDEX_NAME); const storageResult = Cookies.getJSON(CLIENT_SIDE_STORAGE_INDEX_NAME);
result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null; result = storageResult && !isUnd(storageResult[key]) ? storageResult[key] : null;
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
return result; return result;
} }
@ -64,4 +53,4 @@ class CookieDriver
} }
} }
export {CookieDriver, CookieDriver as default}; export { CookieDriver, CookieDriver as default };

View file

@ -1,11 +1,9 @@
import window from 'window'; import window from 'window';
import {isUnd} from 'Common/Utils'; import { isUnd } from 'Common/Utils';
import {isStorageSupported} from 'Storage/RainLoop'; import { isStorageSupported } from 'Storage/RainLoop';
import {CLIENT_SIDE_STORAGE_INDEX_NAME} from 'Common/Consts'; import { CLIENT_SIDE_STORAGE_INDEX_NAME } from 'Common/Consts';
class LocalStorageDriver class LocalStorageDriver {
{
s = null; s = null;
constructor() { constructor() {
@ -18,27 +16,22 @@ class LocalStorageDriver
* @returns {boolean} * @returns {boolean}
*/ */
set(key, data) { set(key, data) {
if (!this.s) if (!this.s) {
{
return false; return false;
} }
let storageResult = null; let storageResult = null;
try try {
{
const storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null; const storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null;
storageResult = null === storageValue ? null : window.JSON.parse(storageValue); storageResult = null === storageValue ? null : window.JSON.parse(storageValue);
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
(storageResult || (storageResult = {}))[key] = data; (storageResult || (storageResult = {}))[key] = data;
try try {
{
this.s.setItem(CLIENT_SIDE_STORAGE_INDEX_NAME, window.JSON.stringify(storageResult)); this.s.setItem(CLIENT_SIDE_STORAGE_INDEX_NAME, window.JSON.stringify(storageResult));
return true; return true;
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
return false; return false;
} }
@ -48,20 +41,16 @@ class LocalStorageDriver
* @returns {*} * @returns {*}
*/ */
get(key) { get(key) {
if (!this.s) if (!this.s) {
{
return null; return null;
} }
try try {
{ const storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null,
const
storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null,
storageResult = null === storageValue ? null : window.JSON.parse(storageValue); storageResult = null === storageValue ? null : window.JSON.parse(storageValue);
return (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null; return storageResult && !isUnd(storageResult[key]) ? storageResult[key] : null;
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
return null; return null;
} }
@ -74,4 +63,4 @@ class LocalStorageDriver
} }
} }
export {LocalStorageDriver, LocalStorageDriver as default}; export { LocalStorageDriver, LocalStorageDriver as default };

View file

@ -1,4 +1,3 @@
export const MESSAGES_PER_PAGE = 20; export const MESSAGES_PER_PAGE = 20;
export const MESSAGES_PER_PAGE_VALUES = [10, 20, 30, 50, 100]; export const MESSAGES_PER_PAGE_VALUES = [10, 20, 30, 50, 100];
@ -38,8 +37,11 @@ export const TOKEN_ERROR_LIMIT = 10;
export const RAINLOOP_TRIAL_KEY = 'RAINLOOP-TRIAL-KEY'; export const RAINLOOP_TRIAL_KEY = 'RAINLOOP-TRIAL-KEY';
/* eslint max-len: 0 */ /* eslint max-len: 0 */
export const DATA_IMAGE_USER_DOT_PIC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC4AAAAuCAYAAABXuSs3AAAHHklEQVRoQ7VZW08bVxCeXRuwIbTGXIwNtBBaqjwgVUiR8lDlbza9qe1DpVZ9aNQ/0KpPeaJK07SpcuEeCEmUAObm21bfrL9lONjexSYrWfbunj37zXdmvpkz9oIgCKTD0Wg0xPd94TDP83Q0zvWa50vzklSrdanVanqf4/D84GBGr+F+Op3S8fqoJxLOdnZgTvsO/nYhenHA+UC7CWF1uXwkb9++ldPTUwVerVbVqFQqpR8YPjQ0JCMjI5LNDijoRgP3PQVu5+5Eor2XGLg7IV4GkIdHJ/LmzRs5ODiIwNbrdR0O0GCcq4Xz4eFhmZyclP7+tDQaIik/BG5XKQn4SwG3zJTLZXn9+rUclI8UHD5YVoDDN8bSzXhONwL48fFxGR4eilzFZT1uFRIB5yT8BqCdnR3Z3d0VP9Un6XRawYJpggVrZBv38ME4XKtUKnLt2jUplUoy1PR/l3U7T6sVSAQcgMAkj8PDQ9ne3pajoyMRL7zeKsYZWHgWYDGmv78/mmdwcFA+mJlSgziHDWrERrsjEXDXegTi1tZW+DLxI2bxIrqFNYTXyDyCFweMAHCwb8e4RnTNuOsqe3t7sra21pTD0Kct666E8XlcZyzw9/RUUXK5nK5oUinUQI6TQ3cynO/v78vq6qrKXCNwlTiJJpyNGc3nZHp6uqV2dwrQWOCtZBDAV1ZWwsQk7f0wiQn5kffbAu/0/KWBYzIC1+XukfGx0RGZmppKlC2tIV0Bh4aDcZW7HhkfH8urLLZL7T2pihvlkMNnz56FiadHxicL41IsFpN41bkxsYxbRdFo9jwB8KdPn14J8KnSpBQKhQs63nPmbCVRcBUAR2Lq1VVmpksyMTFxAXjcEsQybiegESionjx5osCZOeNe1O4+EhCAX7bQSgQcxRHTMgAgcz5+/Dis/hL4uHU3/B4YGNASGHIKxuEql0k+l05AeIAF1vPnz5VxFFmdDlaJrMtZITJeSsXCOTlMunKxjLtMYOKNjQ158eJFuAuKkUOb5sEwgff19SkJUBVkThZUbnXZrtCKBQ6gbnWIkjZpyne3ejAWoGnA7Icz6irvBLgbOMicCM6TkxPx/LAkbXfgWcsazuE2kFRsKD5Z+CiqDumKncpZvieWcS6dDVD8xiYCNflpJdwcdwJOf9airLmVQ7DPzMxIYWLsXGXoVqLt5k0M3K3JUVPDZdbWNzsCp48TPFdvdnZWUz32nDha7bJ63kgAJPzSdRks9/Kf9xMJAQ1gq2NpaUmy2Yz4zar4nQC3xb99AQwCcGzLAAwuhG8YiWvcOKts+r4GOe5nMhm5efOm9lUA3E3vSZJRrKvE0fnPv//Jy5cvo5cTHIPQbSjhOoqq69evS19f6lxDKK4+sVhigZPtKJqbrQeqxd5+WR4+fKgqgT0k2XX3nhiPgETWXFhYkFzuPZ2yVq1GTSOXpE47/VjgNnD4m4GG7/LhsTx69EiwD4Vr2MwIIxgbAH18fKx1yfz8vEogNvGtWnCuhLZa9UTAreVWFsHy/b/+Vrbdl7E5REMQD2jDoUbByty+/ZnU64GkU2HzyJLhktU1cLv8nARgkYS2d3ajAgwG8qU2oLmDZ92CMaOjo7K4uCiZgbDWaRWgnZhPxLhrMUCvr69riwKZk1LHF7XqrWAO9hJxH6ozNzcnCx/PqztZg9mf6SQMscCtm2C5ke4BGMlHWTUp36036AJajDVrFMzBrhhWslQsSrFYiOqVpMriNYIgqFRq2j3FAb/zffT6zuxFXxsNzs3NTXn16lW4gYiW96w1FyedF+83xG/2FNGCRpU4NjamMsn+OZ9xE5RXqdaDdPpib6RWCzuwKF9RxqI2AVNQBwQYJoK0wdBejnqtEikP3pfP51XjUTESl12FqJEKxsEorARYDD44ONTeID7YpsEnrRvQfWAI2e8WfDaTUSIwJ0iBCmFOtOUAHvVMPp/TPwvYFVYFIuP8l+DBgwdaa2Miqwa0GgYwfeMltovbDfh6c1vIgMYcliSsKv4IWFr6VDHxvldvBAH+1sA+cnl5WYOPmmr9ir+1l9I0Cgz0yjhXjfJJ0JROnmezWbl165ayr/5fqwcBNr7IfhjMqKcvESSM4eRcCasQ3bDNObmKPLdGUGpZsN24cUNLBm9zazu4d++e6qpNBFaTuUS26U5dpuR1CxyA7J9ddrMRqlz4pwLLYawymPd++/2PADt2ugcGwq9gCCdhQ96C6xWwa6j1ceuq+I0EhW0i8MAIVJfeL3d/DVD8EKi12P6/2S2jV/EccVB54O/ejz/9HGCpoBBMta5rXMXLu53D1XAwjhXwvvv+h4BAXVe4bOu3O3ChxF08LiZFG3fel199G9CH3fLyqv24NcB44MRhpdK788U3CpyKwsCw590xmfSpzsBt0Fqc3ud3vtZigxWcVZCklVpSiN0w3q5E/h9TGMIUuA3+EQAAAABJRU5ErkJggg=='; export const DATA_IMAGE_USER_DOT_PIC =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC4AAAAuCAYAAABXuSs3AAAHHklEQVRoQ7VZW08bVxCeXRuwIbTGXIwNtBBaqjwgVUiR8lDlbza9qe1DpVZ9aNQ/0KpPeaJK07SpcuEeCEmUAObm21bfrL9lONjexSYrWfbunj37zXdmvpkz9oIgCKTD0Wg0xPd94TDP83Q0zvWa50vzklSrdanVanqf4/D84GBGr+F+Op3S8fqoJxLOdnZgTvsO/nYhenHA+UC7CWF1uXwkb9++ldPTUwVerVbVqFQqpR8YPjQ0JCMjI5LNDijoRgP3PQVu5+5Eor2XGLg7IV4GkIdHJ/LmzRs5ODiIwNbrdR0O0GCcq4Xz4eFhmZyclP7+tDQaIik/BG5XKQn4SwG3zJTLZXn9+rUclI8UHD5YVoDDN8bSzXhONwL48fFxGR4eilzFZT1uFRIB5yT8BqCdnR3Z3d0VP9Un6XRawYJpggVrZBv38ME4XKtUKnLt2jUplUoy1PR/l3U7T6sVSAQcgMAkj8PDQ9ne3pajoyMRL7zeKsYZWHgWYDGmv78/mmdwcFA+mJlSgziHDWrERrsjEXDXegTi1tZW+DLxI2bxIrqFNYTXyDyCFweMAHCwb8e4RnTNuOsqe3t7sra21pTD0Kct666E8XlcZyzw9/RUUXK5nK5oUinUQI6TQ3cynO/v78vq6qrKXCNwlTiJJpyNGc3nZHp6uqV2dwrQWOCtZBDAV1ZWwsQk7f0wiQn5kffbAu/0/KWBYzIC1+XukfGx0RGZmppKlC2tIV0Bh4aDcZW7HhkfH8urLLZL7T2pihvlkMNnz56FiadHxicL41IsFpN41bkxsYxbRdFo9jwB8KdPn14J8KnSpBQKhQs63nPmbCVRcBUAR2Lq1VVmpksyMTFxAXjcEsQybiegESionjx5osCZOeNe1O4+EhCAX7bQSgQcxRHTMgAgcz5+/Dis/hL4uHU3/B4YGNASGHIKxuEql0k+l05AeIAF1vPnz5VxFFmdDlaJrMtZITJeSsXCOTlMunKxjLtMYOKNjQ158eJFuAuKkUOb5sEwgff19SkJUBVkThZUbnXZrtCKBQ6gbnWIkjZpyne3ejAWoGnA7Icz6irvBLgbOMicCM6TkxPx/LAkbXfgWcsazuE2kFRsKD5Z+CiqDumKncpZvieWcS6dDVD8xiYCNflpJdwcdwJOf9airLmVQ7DPzMxIYWLsXGXoVqLt5k0M3K3JUVPDZdbWNzsCp48TPFdvdnZWUz32nDha7bJ63kgAJPzSdRks9/Kf9xMJAQ1gq2NpaUmy2Yz4zar4nQC3xb99AQwCcGzLAAwuhG8YiWvcOKts+r4GOe5nMhm5efOm9lUA3E3vSZJRrKvE0fnPv//Jy5cvo5cTHIPQbSjhOoqq69evS19f6lxDKK4+sVhigZPtKJqbrQeqxd5+WR4+fKgqgT0k2XX3nhiPgETWXFhYkFzuPZ2yVq1GTSOXpE47/VjgNnD4m4GG7/LhsTx69EiwD4Vr2MwIIxgbAH18fKx1yfz8vEogNvGtWnCuhLZa9UTAreVWFsHy/b/+Vrbdl7E5REMQD2jDoUbByty+/ZnU64GkU2HzyJLhktU1cLv8nARgkYS2d3ajAgwG8qU2oLmDZ92CMaOjo7K4uCiZgbDWaRWgnZhPxLhrMUCvr69riwKZk1LHF7XqrWAO9hJxH6ozNzcnCx/PqztZg9mf6SQMscCtm2C5ke4BGMlHWTUp36036AJajDVrFMzBrhhWslQsSrFYiOqVpMriNYIgqFRq2j3FAb/zffT6zuxFXxsNzs3NTXn16lW4gYiW96w1FyedF+83xG/2FNGCRpU4NjamMsn+OZ9xE5RXqdaDdPpib6RWCzuwKF9RxqI2AVNQBwQYJoK0wdBejnqtEikP3pfP51XjUTESl12FqJEKxsEorARYDD44ONTeID7YpsEnrRvQfWAI2e8WfDaTUSIwJ0iBCmFOtOUAHvVMPp/TPwvYFVYFIuP8l+DBgwdaa2Miqwa0GgYwfeMltovbDfh6c1vIgMYcliSsKv4IWFr6VDHxvldvBAH+1sA+cnl5WYOPmmr9ir+1l9I0Cgz0yjhXjfJJ0JROnmezWbl165ayr/5fqwcBNr7IfhjMqKcvESSM4eRcCasQ3bDNObmKPLdGUGpZsN24cUNLBm9zazu4d++e6qpNBFaTuUS26U5dpuR1CxyA7J9ddrMRqlz4pwLLYawymPd++/2PADt2ugcGwq9gCCdhQ96C6xWwa6j1ceuq+I0EhW0i8MAIVJfeL3d/DVD8EKi12P6/2S2jV/EccVB54O/ejz/9HGCpoBBMta5rXMXLu53D1XAwjhXwvvv+h4BAXVe4bOu3O3ChxF08LiZFG3fel199G9CH3fLyqv24NcB44MRhpdK788U3CpyKwsCw590xmfSpzsBt0Fqc3ud3vtZigxWcVZCklVpSiN0w3q5E/h9TGMIUuA3+EQAAAABJRU5ErkJggg==';
export const DATA_IMAGE_TRANSP_PIC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII='; export const DATA_IMAGE_TRANSP_PIC =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=';
export const DATA_IMAGE_LAZY_PLACEHOLDER_PIC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC'; export const DATA_IMAGE_LAZY_PLACEHOLDER_PIC =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC';

View file

@ -1,4 +1,3 @@
/* eslint quote-props: 0 */ /* eslint quote-props: 0 */
/** /**
@ -387,7 +386,6 @@ export const SignedVerifyStatus = {
* @enum {number} * @enum {number}
*/ */
export const ContactPropertyType = { export const ContactPropertyType = {
'Unknown': 0, 'Unknown': 0,
'FullName': 10, 'FullName': 10,

View file

@ -1,6 +1,5 @@
import _ from '_'; import _ from '_';
import {isObject, isUnd} from 'Common/Utils'; import { isObject, isUnd } from 'Common/Utils';
import * as Plugins from 'Common/Plugins'; import * as Plugins from 'Common/Plugins';
const SUBS = {}; const SUBS = {};
@ -10,21 +9,16 @@ const SUBS = {};
* @param {Function} func * @param {Function} func
* @param {Object=} context * @param {Object=} context
*/ */
export function sub(name, func, context) export function sub(name, func, context) {
{ if (isObject(name)) {
if (isObject(name))
{
context = func || null; context = func || null;
func = null; func = null;
_.each(name, (subFunc, subName) => { _.each(name, (subFunc, subName) => {
sub(subName, subFunc, context); sub(subName, subFunc, context);
}); });
} } else {
else if (isUnd(SUBS[name])) {
{
if (isUnd(SUBS[name]))
{
SUBS[name] = []; SUBS[name] = [];
} }
@ -36,15 +30,12 @@ export function sub(name, func, context)
* @param {string} name * @param {string} name
* @param {Array=} args * @param {Array=} args
*/ */
export function pub(name, args) export function pub(name, args) {
{
Plugins.runHook('rl-pub', [name, args]); Plugins.runHook('rl-pub', [name, args]);
if (!isUnd(SUBS[name])) if (!isUnd(SUBS[name])) {
{
_.each(SUBS[name], (items) => { _.each(SUBS[name], (items) => {
if (items[0]) if (items[0]) {
{
items[0].apply(items[1] || null, args || []); items[0].apply(items[1] || null, args || []);
} }
}); });

View file

@ -3,12 +3,12 @@ import _ from '_';
import $ from '$'; import $ from '$';
import key from 'key'; import key from 'key';
import ko from 'ko'; import ko from 'ko';
import {KeyState} from 'Common/Enums'; import { KeyState } from 'Common/Enums';
const $win = $(window); const $win = $(window);
$win.__sizes = [0, 0]; $win.__sizes = [0, 0];
export {$win}; export { $win };
export const $doc = $(window.document); export const $doc = $(window.document);
@ -19,9 +19,12 @@ export const $body = $('body');
export const $div = $('<div></div>'); export const $div = $('<div></div>');
export const $hcont = $('<div></div>'); export const $hcont = $('<div></div>');
$hcont.attr('area', 'hidden').css({position: 'absolute', left: -5000}).appendTo($body); $hcont
.attr('area', 'hidden')
.css({ position: 'absolute', left: -5000 })
.appendTo($body);
export const startMicrotime = (new window.Date()).getTime(); export const startMicrotime = new window.Date().getTime();
/** /**
* @type {boolean} * @type {boolean}
@ -31,7 +34,7 @@ export const community = RL_COMMUNITY;
/** /**
* @type {?} * @type {?}
*/ */
export const dropdownVisibility = ko.observable(false).extend({rateLimit: 0}); export const dropdownVisibility = ko.observable(false).extend({ rateLimit: 0 });
/** /**
* @type {boolean} * @type {boolean}
@ -41,8 +44,8 @@ export const useKeyboardShortcuts = ko.observable(true);
/** /**
* @type {string} * @type {string}
*/ */
export const sUserAgent = 'navigator' in window && 'userAgent' in window.navigator && export const sUserAgent =
window.navigator.userAgent.toLowerCase() || ''; ('navigator' in window && 'userAgent' in window.navigator && window.navigator.userAgent.toLowerCase()) || '';
/** /**
* @type {boolean} * @type {boolean}
@ -77,7 +80,8 @@ export const bDisableNanoScroll = bMobileDevice;
/** /**
* @type {boolean} * @type {boolean}
*/ */
export const bAnimationSupported = !bMobileDevice && $html.hasClass('csstransitions') && $html.hasClass('cssanimations'); export const bAnimationSupported =
!bMobileDevice && $html.hasClass('csstransitions') && $html.hasClass('cssanimations');
/** /**
* @type {boolean} * @type {boolean}
@ -87,7 +91,8 @@ export const bXMLHttpRequestSupported = !!window.XMLHttpRequest;
/** /**
* @type {boolean} * @type {boolean}
*/ */
export const bIsHttps = window.document && window.document.location ? 'https:' === window.document.location.protocol : false; export const bIsHttps =
window.document && window.document.location ? 'https:' === window.document.location.protocol : false;
/** /**
* @type {Object} * @type {Object}
@ -98,15 +103,15 @@ export const htmlEditorDefaultConfig = {
'customConfig': '', 'customConfig': '',
'contentsCss': '', 'contentsCss': '',
'toolbarGroups': [ 'toolbarGroups': [
{name: 'spec'}, { name: 'spec' },
{name: 'styles'}, { name: 'styles' },
{name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'bidi']}, { name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'bidi'] },
{name: 'colors'}, { name: 'colors' },
bMobileDevice ? {} : {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']}, bMobileDevice ? {} : { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align'] },
{name: 'links'}, { name: 'links' },
{name: 'insert'}, { name: 'insert' },
{name: 'document', groups: ['mode', 'document', 'doctools']}, { name: 'document', groups: ['mode', 'document', 'doctools'] },
{name: 'others'} { name: 'others' }
], ],
'removePlugins': 'liststyle', 'removePlugins': 'liststyle',
@ -171,17 +176,15 @@ export const htmlEditorLangsMap = {
*/ */
let bAllowPdfPreview = !bMobileDevice; let bAllowPdfPreview = !bMobileDevice;
if (bAllowPdfPreview && window.navigator && window.navigator.mimeTypes) if (bAllowPdfPreview && window.navigator && window.navigator.mimeTypes) {
{
bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, (type) => type && 'application/pdf' === type.type); bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, (type) => type && 'application/pdf' === type.type);
if (!bAllowPdfPreview) if (!bAllowPdfPreview) {
{
bAllowPdfPreview = 'undefined' !== typeof window.navigator.mimeTypes['application/pdf']; bAllowPdfPreview = 'undefined' !== typeof window.navigator.mimeTypes['application/pdf'];
} }
} }
export {bAllowPdfPreview}; export { bAllowPdfPreview };
export const VIEW_MODELS = { export const VIEW_MODELS = {
settings: [], settings: [],
@ -222,26 +225,21 @@ export const keyScopeFake = ko.observable(KeyState.All);
export const keyScope = ko.computed({ export const keyScope = ko.computed({
read: () => keyScopeFake(), read: () => keyScopeFake(),
write: (value) => { write: (value) => {
if (KeyState.Menu !== value) {
if (KeyState.Menu !== value) if (KeyState.Compose === value) {
{
if (KeyState.Compose === value)
{
// disableKeyFilter // disableKeyFilter
key.filter = () => useKeyboardShortcuts(); key.filter = () => useKeyboardShortcuts();
} } else {
else
{
// restoreKeyFilter // restoreKeyFilter
key.filter = (event) => { key.filter = (event) => {
if (useKeyboardShortcuts()) {
if (useKeyboardShortcuts()) const el = event.target || event.srcElement,
{
const
el = event.target || event.srcElement,
tagName = el ? el.tagName.toUpperCase() : ''; tagName = el ? el.tagName.toUpperCase() : '';
return !('INPUT' === tagName || 'SELECT' === tagName || 'TEXTAREA' === tagName || return !(
'INPUT' === tagName ||
'SELECT' === tagName ||
'TEXTAREA' === tagName ||
(el && 'DIV' === tagName && ('editorHtmlArea' === el.className || 'true' === '' + el.contentEditable)) (el && 'DIV' === tagName && ('editorHtmlArea' === el.className || 'true' === '' + el.contentEditable))
); );
} }
@ -251,8 +249,7 @@ export const keyScope = ko.computed({
} }
keyScopeFake(value); keyScopeFake(value);
if (dropdownVisibility()) if (dropdownVisibility()) {
{
value = KeyState.Menu; value = KeyState.Menu;
} }
} }
@ -262,17 +259,14 @@ export const keyScope = ko.computed({
}); });
keyScopeReal.subscribe((value) => { keyScopeReal.subscribe((value) => {
// window.console.log('keyScope=' + sValue); // DEBUG // window.console.log('keyScope=' + sValue); // DEBUG
key.setScope(value); key.setScope(value);
}); });
dropdownVisibility.subscribe((value) => { dropdownVisibility.subscribe((value) => {
if (value) if (value) {
{
keyScope(KeyState.Menu); keyScope(KeyState.Menu);
} } else if (KeyState.Menu === key.getScope()) {
else if (KeyState.Menu === key.getScope())
{
keyScope(keyScopeFake()); keyScope(keyScopeFake());
} }
}); });

View file

@ -1,13 +1,11 @@
import window from 'window'; import window from 'window';
import _ from '_'; import _ from '_';
import $ from '$'; import $ from '$';
import {htmlEditorDefaultConfig, htmlEditorLangsMap} from 'Common/Globals'; import { htmlEditorDefaultConfig, htmlEditorLangsMap } from 'Common/Globals';
import {EventKeyCode, Magics} from 'Common/Enums'; import { EventKeyCode, Magics } from 'Common/Enums';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
class HtmlEditor class HtmlEditor {
{
editor; editor;
blurTimer = 0; blurTimer = 0;
@ -29,8 +27,7 @@ class HtmlEditor
* @param {Function=} onReady * @param {Function=} onReady
* @param {Function=} onModeChange * @param {Function=} onModeChange
*/ */
constructor(element, onBlur = null, onReady = null, onModeChange = null) constructor(element, onBlur = null, onReady = null, onModeChange = null) {
{
this.onBlur = onBlur; this.onBlur = onBlur;
this.onReady = onReady; this.onReady = onReady;
this.onModeChange = onModeChange; this.onModeChange = onModeChange;
@ -44,15 +41,13 @@ class HtmlEditor
} }
runOnBlur() { runOnBlur() {
if (this.onBlur) if (this.onBlur) {
{
this.onBlur(); this.onBlur();
} }
} }
blurTrigger() { blurTrigger() {
if (this.onBlur) if (this.onBlur) {
{
window.clearTimeout(this.blurTimer); window.clearTimeout(this.blurTimer);
this.blurTimer = window.setTimeout(() => { this.blurTimer = window.setTimeout(() => {
this.runOnBlur(); this.runOnBlur();
@ -61,8 +56,7 @@ class HtmlEditor
} }
focusTrigger() { focusTrigger() {
if (this.onBlur) if (this.onBlur) {
{
window.clearTimeout(this.blurTimer); window.clearTimeout(this.blurTimer);
} }
} }
@ -78,8 +72,7 @@ class HtmlEditor
* @returns {void} * @returns {void}
*/ */
clearCachedSignature() { clearCachedSignature() {
if (this.editor) if (this.editor) {
{
this.editor.execCommand('insertSignature', { this.editor.execCommand('insertSignature', {
clearCache: true clearCache: true
}); });
@ -93,8 +86,7 @@ class HtmlEditor
* @returns {void} * @returns {void}
*/ */
setSignature(signature, html, insertBefore = false) { setSignature(signature, html, insertBefore = false) {
if (this.editor) if (this.editor) {
{
this.editor.execCommand('insertSignature', { this.editor.execCommand('insertSignature', {
isHtml: html, isHtml: html,
insertBefore: insertBefore, insertBefore: insertBefore,
@ -111,8 +103,7 @@ class HtmlEditor
} }
resetDirty() { resetDirty() {
if (this.editor) if (this.editor) {
{
this.editor.resetDirty(); this.editor.resetDirty();
} }
} }
@ -122,24 +113,19 @@ class HtmlEditor
* @returns {string} * @returns {string}
*/ */
getData(wrapIsHtml = false) { getData(wrapIsHtml = false) {
let result = ''; let result = '';
if (this.editor) if (this.editor) {
{ try {
try if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain) {
{
if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
{
result = this.editor.__plain.getRawData(); result = this.editor.__plain.getRawData();
} else {
result = wrapIsHtml
? '<div data-html-editor-font-wrapper="true" style="font-family: arial, sans-serif; font-size: 13px;">' +
this.editor.getData() +
'</div>'
: this.editor.getData();
} }
else } catch (e) {} // eslint-disable-line no-empty
{
result = wrapIsHtml ?
'<div data-html-editor-font-wrapper="true" style="font-family: arial, sans-serif; font-size: 13px;">' +
this.editor.getData() + '</div>' : this.editor.getData();
}
}
catch (e) {} // eslint-disable-line no-empty
} }
return result; return result;
@ -154,271 +140,217 @@ class HtmlEditor
} }
modeToggle(plain, resize) { modeToggle(plain, resize) {
if (this.editor) if (this.editor) {
{
try { try {
if (plain) if (plain) {
{ if ('plain' === this.editor.mode) {
if ('plain' === this.editor.mode)
{
this.editor.setMode('wysiwyg'); this.editor.setMode('wysiwyg');
} }
} } else if ('wysiwyg' === this.editor.mode) {
else if ('wysiwyg' === this.editor.mode)
{
this.editor.setMode('plain'); this.editor.setMode('plain');
} }
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
if (resize) if (resize) {
{
this.resize(); this.resize();
} }
} }
} }
setHtmlOrPlain(text, focus) { setHtmlOrPlain(text, focus) {
if (':HTML:' === text.substr(0, 6)) if (':HTML:' === text.substr(0, 6)) {
{
this.setHtml(text.substr(6), focus); this.setHtml(text.substr(6), focus);
} } else {
else
{
this.setPlain(text, focus); this.setPlain(text, focus);
} }
} }
setHtml(html, focus) { setHtml(html, focus) {
if (this.editor && this.__inited) if (this.editor && this.__inited) {
{
this.clearCachedSignature(); this.clearCachedSignature();
this.modeToggle(true); this.modeToggle(true);
html = html.replace(/<p[^>]*><\/p>/ig, ''); html = html.replace(/<p[^>]*><\/p>/gi, '');
try { try {
this.editor.setData(html); this.editor.setData(html);
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
if (focus) if (focus) {
{
this.focus(); this.focus();
} }
} }
} }
replaceHtml(find, replaceHtml) { replaceHtml(find, replaceHtml) {
if (this.editor && this.__inited && 'wysiwyg' === this.editor.mode) if (this.editor && this.__inited && 'wysiwyg' === this.editor.mode) {
{
try { try {
this.editor.setData(this.editor.getData().replace(find, replaceHtml)); this.editor.setData(this.editor.getData().replace(find, replaceHtml));
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
} }
} }
setPlain(plain, focus) { setPlain(plain, focus) {
if (this.editor && this.__inited) if (this.editor && this.__inited) {
{
this.clearCachedSignature(); this.clearCachedSignature();
this.modeToggle(false); this.modeToggle(false);
if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain) if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain) {
{
this.editor.__plain.setRawData(plain); this.editor.__plain.setRawData(plain);
} } else {
else
{
try { try {
this.editor.setData(plain); this.editor.setData(plain);
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
} }
if (focus) if (focus) {
{
this.focus(); this.focus();
} }
} }
} }
init() { init() {
if (this.element && !this.editor) if (this.element && !this.editor) {
{ const initFunc = () => {
const const config = htmlEditorDefaultConfig,
initFunc = () => { language = Settings.settingsGet('Language'),
allowSource = !!Settings.appSettingsGet('allowHtmlEditorSourceButton'),
biti = !!Settings.appSettingsGet('allowHtmlEditorBitiButtons');
const if ((allowSource || !biti) && !config.toolbarGroups.__cfgInited) {
config = htmlEditorDefaultConfig, config.toolbarGroups.__cfgInited = true;
language = Settings.settingsGet('Language'),
allowSource = !!Settings.appSettingsGet('allowHtmlEditorSourceButton'),
biti = !!Settings.appSettingsGet('allowHtmlEditorBitiButtons');
if ((allowSource || !biti) && !config.toolbarGroups.__cfgInited) if (allowSource) {
{ config.removeButtons = config.removeButtons.replace(',Source', '');
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; if (!biti) {
config.shiftEnterMode = window.CKEDITOR.ENTER_P; config.removePlugins += (config.removePlugins ? ',' : '') + 'bidi';
}
}
config.language = htmlEditorLangsMap[(language || 'en').toLowerCase()] || 'en'; config.enterMode = window.CKEDITOR.ENTER_BR;
if (window.CKEDITOR.env) config.shiftEnterMode = window.CKEDITOR.ENTER_P;
{
window.CKEDITOR.env.isCompatible = true; config.language = htmlEditorLangsMap[(language || 'en').toLowerCase()] || 'en';
if (window.CKEDITOR.env) {
window.CKEDITOR.env.isCompatible = true;
}
this.editor = window.CKEDITOR.appendTo(this.element, config);
this.editor.on('key', (event) => {
if (event && event.data && EventKeyCode.Tab === event.data.keyCode) {
return false;
} }
this.editor = window.CKEDITOR.appendTo(this.element, config); return true;
});
this.editor.on('key', (event) => { this.editor.on('blur', () => {
if (event && event.data && EventKeyCode.Tab === event.data.keyCode) this.blurTrigger();
{ });
return false;
}
return true; this.editor.on('mode', () => {
}); this.blurTrigger();
if (this.onModeChange) {
this.onModeChange('plain' !== this.editor.mode);
}
});
this.editor.on('blur', () => { this.editor.on('focus', () => {
this.blurTrigger(); this.focusTrigger();
}); });
this.editor.on('mode', () => { if (window.FileReader) {
this.blurTrigger(); this.editor.on('drop', (event) => {
if (this.onModeChange) if (0 < event.data.dataTransfer.getFilesCount()) {
{ const file = event.data.dataTransfer.getFile(0);
this.onModeChange('plain' !== this.editor.mode); if (file && window.FileReader && event.data.dataTransfer.id && file.type && file.type.match(/^image/i)) {
} const id = event.data.dataTransfer.id,
}); imageId = `[img=${id}]`,
reader = new window.FileReader();
this.editor.on('focus', () => { reader.onloadend = () => {
this.focusTrigger(); if (reader.result) {
}); this.replaceHtml(imageId, `<img src="${reader.result}" />`);
}
};
if (window.FileReader) reader.readAsDataURL(file);
{
this.editor.on('drop', (event) => {
if (0 < event.data.dataTransfer.getFilesCount())
{
const file = event.data.dataTransfer.getFile(0);
if (file && window.FileReader && event.data.dataTransfer.id &&
file.type && file.type.match(/^image/i))
{
const
id = event.data.dataTransfer.id,
imageId = `[img=${id}]`,
reader = new window.FileReader();
reader.onloadend = () => { event.data.dataTransfer.setData('text/html', imageId);
if (reader.result)
{
this.replaceHtml(imageId, `<img src="${reader.result}" />`);
}
};
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.editor.on('instanceReady', () => { this.__resizable = true;
this.__inited = true;
if (this.editor.removeMenuItem) this.resize();
{
this.editor.removeMenuItem('cut');
this.editor.removeMenuItem('copy');
this.editor.removeMenuItem('paste');
}
this.__resizable = true; if (this.onReady) {
this.__inited = true; this.onReady();
}
});
};
this.resize(); if (window.CKEDITOR) {
if (this.onReady)
{
this.onReady();
}
});
};
if (window.CKEDITOR)
{
initFunc(); initFunc();
} } else {
else
{
window.__initEditor = initFunc; window.__initEditor = initFunc;
} }
} }
} }
focus() { focus() {
if (this.editor) if (this.editor) {
{
try { try {
this.editor.focus(); this.editor.focus();
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
} }
} }
hasFocus() { hasFocus() {
if (this.editor) if (this.editor) {
{
try { try {
return !!this.editor.focusManager.hasFocus; return !!this.editor.focusManager.hasFocus;
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
} }
return false; return false;
} }
blur() { blur() {
if (this.editor) if (this.editor) {
{
try { try {
this.editor.focusManager.blur(true); this.editor.focusManager.blur(true);
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
} }
} }
resizeEditor() { resizeEditor() {
if (this.editor && this.__resizable) if (this.editor && this.__resizable) {
{
try { try {
this.editor.resize(this.$element.width(), this.$element.innerHeight()); this.editor.resize(this.$element.width(), this.$element.innerHeight());
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
} }
} }
setReadOnly(value) { setReadOnly(value) {
if (this.editor) if (this.editor) {
{
try { try {
this.editor.setReadOnly(!!value); this.editor.setReadOnly(!!value);
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
} }
} }
@ -427,4 +359,4 @@ class HtmlEditor
} }
} }
export {HtmlEditor, HtmlEditor as default}; export { HtmlEditor, HtmlEditor as default };

View file

@ -1,4 +1,3 @@
import window from 'window'; import window from 'window';
// let rainloopCaches = window.caches && window.caches.open ? window.caches : null; // let rainloopCaches = window.caches && window.caches.open ? window.caches : null;
@ -9,19 +8,15 @@ import window from 'window';
* @returns {Promise} * @returns {Promise}
*/ */
export function jassl(src, async = false) { export function jassl(src, async = false) {
if (!window.Promise || !window.Promise.all) {
if (!window.Promise || !window.Promise.all)
{
throw new Error('Promises are not available your environment.'); throw new Error('Promises are not available your environment.');
} }
if (!src) if (!src) {
{
throw new Error('src should not be empty.'); throw new Error('src should not be empty.');
} }
return new window.Promise((resolve, reject) => { return new window.Promise((resolve, reject) => {
const element = window.document.createElement('script'); const element = window.document.createElement('script');
element.onload = () => { element.onload = () => {
@ -36,7 +31,7 @@ export function jassl(src, async = false) {
element.src = src; element.src = src;
window.document.body.appendChild(element); window.document.body.appendChild(element);
})/* .then((s) => { }) /* .then((s) => {
const found = s && rainloopCaches ? s.match(/rainloop\/v\/([^\/]+)\/static\//) : null; const found = s && rainloopCaches ? s.match(/rainloop\/v\/([^\/]+)\/static\//) : null;
if (found && found[1]) if (found && found[1])

View file

@ -1,20 +1,15 @@
import window from 'window'; import window from 'window';
import {pString, pInt, isUnd, isNormal, trim, encodeURIComponent} from 'Common/Utils'; import { pString, pInt, isUnd, isNormal, trim, encodeURIComponent } from 'Common/Utils';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
const const ROOT = './',
ROOT = './',
HASH_PREFIX = '#/', HASH_PREFIX = '#/',
SERVER_PREFIX = './?', SERVER_PREFIX = './?',
SUB_QUERY_PREFIX = '&q[]=', SUB_QUERY_PREFIX = '&q[]=',
VERSION = Settings.appSettingsGet('version'), VERSION = Settings.appSettingsGet('version'),
WEB_PREFIX = Settings.appSettingsGet('webPath') || '', WEB_PREFIX = Settings.appSettingsGet('webPath') || '',
VERSION_PREFIX = Settings.appSettingsGet('webVersionPath') || 'rainloop/v/' + VERSION + '/', VERSION_PREFIX = Settings.appSettingsGet('webVersionPath') || 'rainloop/v/' + VERSION + '/',
STATIC_PREFIX = VERSION_PREFIX + 'static/', STATIC_PREFIX = VERSION_PREFIX + 'static/',
ADMIN_HOST_USE = !!Settings.appSettingsGet('adminHostUse'), ADMIN_HOST_USE = !!Settings.appSettingsGet('adminHostUse'),
ADMIN_PATH = Settings.appSettingsGet('adminPath') || 'admin'; ADMIN_PATH = Settings.appSettingsGet('adminPath') || 'admin';
@ -23,16 +18,14 @@ let AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0';
/** /**
* @returns {void} * @returns {void}
*/ */
export function populateAuthSuffix() export function populateAuthSuffix() {
{
AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0'; AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0';
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function subQueryPrefix() export function subQueryPrefix() {
{
return SUB_QUERY_PREFIX; return SUB_QUERY_PREFIX;
} }
@ -40,24 +33,21 @@ export function subQueryPrefix()
* @param {string=} startupUrl * @param {string=} startupUrl
* @returns {string} * @returns {string}
*/ */
export function root(startupUrl = '') export function root(startupUrl = '') {
{
return HASH_PREFIX + pString(startupUrl); return HASH_PREFIX + pString(startupUrl);
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function rootAdmin() export function rootAdmin() {
{
return ADMIN_HOST_USE ? ROOT : SERVER_PREFIX + ADMIN_PATH; return ADMIN_HOST_USE ? ROOT : SERVER_PREFIX + ADMIN_PATH;
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function rootUser() export function rootUser() {
{
return ROOT; return ROOT;
} }
@ -67,10 +57,21 @@ export function rootUser()
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @returns {string} * @returns {string}
*/ */
export function attachmentRaw(type, download, customSpecSuffix) export function attachmentRaw(type, download, customSpecSuffix) {
{
customSpecSuffix = isUnd(customSpecSuffix) ? AUTH_PREFIX : customSpecSuffix; customSpecSuffix = isUnd(customSpecSuffix) ? AUTH_PREFIX : customSpecSuffix;
return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + customSpecSuffix + '/' + type + '/' + SUB_QUERY_PREFIX + '/' + download; return (
SERVER_PREFIX +
'/Raw/' +
SUB_QUERY_PREFIX +
'/' +
customSpecSuffix +
'/' +
type +
'/' +
SUB_QUERY_PREFIX +
'/' +
download
);
} }
/** /**
@ -78,8 +79,7 @@ export function attachmentRaw(type, download, customSpecSuffix)
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @returns {string} * @returns {string}
*/ */
export function attachmentDownload(download, customSpecSuffix) export function attachmentDownload(download, customSpecSuffix) {
{
return attachmentRaw('Download', download, customSpecSuffix); return attachmentRaw('Download', download, customSpecSuffix);
} }
@ -88,8 +88,7 @@ export function attachmentDownload(download, customSpecSuffix)
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @returns {string} * @returns {string}
*/ */
export function attachmentPreview(download, customSpecSuffix) export function attachmentPreview(download, customSpecSuffix) {
{
return attachmentRaw('View', download, customSpecSuffix); return attachmentRaw('View', download, customSpecSuffix);
} }
@ -98,8 +97,7 @@ export function attachmentPreview(download, customSpecSuffix)
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @returns {string} * @returns {string}
*/ */
export function attachmentThumbnailPreview(download, customSpecSuffix) export function attachmentThumbnailPreview(download, customSpecSuffix) {
{
return attachmentRaw('ViewThumbnail', download, customSpecSuffix); return attachmentRaw('ViewThumbnail', download, customSpecSuffix);
} }
@ -108,8 +106,7 @@ export function attachmentThumbnailPreview(download, customSpecSuffix)
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @returns {string} * @returns {string}
*/ */
export function attachmentPreviewAsPlain(download, customSpecSuffix) export function attachmentPreviewAsPlain(download, customSpecSuffix) {
{
return attachmentRaw('ViewAsPlain', download, customSpecSuffix); return attachmentRaw('ViewAsPlain', download, customSpecSuffix);
} }
@ -118,8 +115,7 @@ export function attachmentPreviewAsPlain(download, customSpecSuffix)
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @returns {string} * @returns {string}
*/ */
export function attachmentFramed(download, customSpecSuffix) export function attachmentFramed(download, customSpecSuffix) {
{
return attachmentRaw('FramedView', download, customSpecSuffix); return attachmentRaw('FramedView', download, customSpecSuffix);
} }
@ -127,40 +123,35 @@ export function attachmentFramed(download, customSpecSuffix)
* @param {string} type * @param {string} type
* @returns {string} * @returns {string}
*/ */
export function serverRequest(type) export function serverRequest(type) {
{
return SERVER_PREFIX + '/' + type + '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/'; return SERVER_PREFIX + '/' + type + '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/';
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function upload() export function upload() {
{
return serverRequest('Upload'); return serverRequest('Upload');
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function uploadContacts() export function uploadContacts() {
{
return serverRequest('UploadContacts'); return serverRequest('UploadContacts');
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function uploadBackground() export function uploadBackground() {
{
return serverRequest('UploadBackground'); return serverRequest('UploadBackground');
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function append() export function append() {
{
return serverRequest('Append'); return serverRequest('Append');
} }
@ -168,8 +159,7 @@ export function append()
* @param {string} email * @param {string} email
* @returns {string} * @returns {string}
*/ */
export function change(email) export function change(email) {
{
return serverRequest('Change') + encodeURIComponent(email) + '/'; return serverRequest('Change') + encodeURIComponent(email) + '/';
} }
@ -177,8 +167,7 @@ export function change(email)
* @param {string} add * @param {string} add
* @returns {string} * @returns {string}
*/ */
export function ajax(add) export function ajax(add) {
{
return serverRequest('Ajax') + add; return serverRequest('Ajax') + add;
} }
@ -186,26 +175,35 @@ export function ajax(add)
* @param {string} requestHash * @param {string} requestHash
* @returns {string} * @returns {string}
*/ */
export function messageViewLink(requestHash) export function messageViewLink(requestHash) {
{ return (
return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/ViewAsPlain/' + SUB_QUERY_PREFIX + '/' + requestHash; SERVER_PREFIX +
'/Raw/' +
SUB_QUERY_PREFIX +
'/' +
AUTH_PREFIX +
'/ViewAsPlain/' +
SUB_QUERY_PREFIX +
'/' +
requestHash
);
} }
/** /**
* @param {string} requestHash * @param {string} requestHash
* @returns {string} * @returns {string}
*/ */
export function messageDownloadLink(requestHash) export function messageDownloadLink(requestHash) {
{ return (
return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/Download/' + SUB_QUERY_PREFIX + '/' + requestHash; SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/Download/' + SUB_QUERY_PREFIX + '/' + requestHash
);
} }
/** /**
* @param {string} email * @param {string} email
* @returns {string} * @returns {string}
*/ */
export function avatarLink(email) export function avatarLink(email) {
{
return SERVER_PREFIX + '/Raw/0/Avatar/' + encodeURIComponent(email) + '/'; return SERVER_PREFIX + '/Raw/0/Avatar/' + encodeURIComponent(email) + '/';
} }
@ -213,8 +211,7 @@ export function avatarLink(email)
* @param {string} hash * @param {string} hash
* @returns {string} * @returns {string}
*/ */
export function publicLink(hash) export function publicLink(hash) {
{
return SERVER_PREFIX + '/Raw/0/Public/' + hash + '/'; return SERVER_PREFIX + '/Raw/0/Public/' + hash + '/';
} }
@ -222,16 +219,16 @@ export function publicLink(hash)
* @param {string} hash * @param {string} hash
* @returns {string} * @returns {string}
*/ */
export function userBackground(hash) export function userBackground(hash) {
{ return (
return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/UserBackground/' + SUB_QUERY_PREFIX + '/' + hash; SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/UserBackground/' + SUB_QUERY_PREFIX + '/' + hash
);
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function phpInfo() export function phpInfo() {
{
return SERVER_PREFIX + '/Info'; return SERVER_PREFIX + '/Info';
} }
@ -240,24 +237,21 @@ export function phpInfo()
* @param {boolean} isAdmin * @param {boolean} isAdmin
* @returns {string} * @returns {string}
*/ */
export function langLink(lang, isAdmin) export function langLink(lang, isAdmin) {
{
return SERVER_PREFIX + '/Lang/0/' + (isAdmin ? 'Admin' : 'App') + '/' + window.encodeURI(lang) + '/' + VERSION + '/'; return SERVER_PREFIX + '/Lang/0/' + (isAdmin ? 'Admin' : 'App') + '/' + window.encodeURI(lang) + '/' + VERSION + '/';
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function exportContactsVcf() export function exportContactsVcf() {
{
return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/ContactsVcf/'; return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/ContactsVcf/';
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function exportContactsCsv() export function exportContactsCsv() {
{
return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/ContactsCsv/'; return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/ContactsCsv/';
} }
@ -265,44 +259,43 @@ export function exportContactsCsv()
* @param {boolean} xauth = false * @param {boolean} xauth = false
* @returns {string} * @returns {string}
*/ */
export function socialGoogle(xauth = false) export function socialGoogle(xauth = false) {
{ return (
return SERVER_PREFIX + 'SocialGoogle' + SERVER_PREFIX +
('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '') + (xauth ? '&xauth=1' : ''); 'SocialGoogle' +
('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '') +
(xauth ? '&xauth=1' : '')
);
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function socialTwitter() export function socialTwitter() {
{ return SERVER_PREFIX + 'SocialTwitter' + ('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '');
return SERVER_PREFIX + 'SocialTwitter' +
('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '');
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function socialFacebook() export function socialFacebook() {
{ return (
return SERVER_PREFIX + 'SocialFacebook' + SERVER_PREFIX + 'SocialFacebook' + ('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '')
('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : ''); );
} }
/** /**
* @param {string} path * @param {string} path
* @returns {string} * @returns {string}
*/ */
export function staticPrefix(path) export function staticPrefix(path) {
{
return STATIC_PREFIX + path; return STATIC_PREFIX + path;
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function emptyContactPic() export function emptyContactPic() {
{
return staticPrefix('css/images/empty-contact.png'); return staticPrefix('css/images/empty-contact.png');
} }
@ -310,40 +303,35 @@ export function emptyContactPic()
* @param {string} fileName * @param {string} fileName
* @returns {string} * @returns {string}
*/ */
export function sound(fileName) export function sound(fileName) {
{
return staticPrefix('sounds/' + fileName); return staticPrefix('sounds/' + fileName);
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function notificationMailIcon() export function notificationMailIcon() {
{
return staticPrefix('css/images/icom-message-notification.png'); return staticPrefix('css/images/icom-message-notification.png');
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function openPgpJs() export function openPgpJs() {
{
return staticPrefix('js/min/openpgp.min.js'); return staticPrefix('js/min/openpgp.min.js');
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function openPgpWorkerJs() export function openPgpWorkerJs() {
{
return staticPrefix('js/min/openpgp.worker.min.js'); return staticPrefix('js/min/openpgp.worker.min.js');
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function openPgpWorkerPath() export function openPgpWorkerPath() {
{
return staticPrefix('js/min/'); return staticPrefix('js/min/');
} }
@ -351,11 +339,9 @@ export function openPgpWorkerPath()
* @param {string} theme * @param {string} theme
* @returns {string} * @returns {string}
*/ */
export function themePreviewLink(theme) export function themePreviewLink(theme) {
{
let prefix = VERSION_PREFIX; let prefix = VERSION_PREFIX;
if ('@custom' === theme.substr(-7)) if ('@custom' === theme.substr(-7)) {
{
theme = trim(theme.substring(0, theme.length - 7)); theme = trim(theme.substring(0, theme.length - 7));
prefix = WEB_PREFIX; prefix = WEB_PREFIX;
} }
@ -367,8 +353,7 @@ export function themePreviewLink(theme)
* @param {string} inboxFolderName = 'INBOX' * @param {string} inboxFolderName = 'INBOX'
* @returns {string} * @returns {string}
*/ */
export function inbox(inboxFolderName = 'INBOX') export function inbox(inboxFolderName = 'INBOX') {
{
return HASH_PREFIX + 'mailbox/' + inboxFolderName; return HASH_PREFIX + 'mailbox/' + inboxFolderName;
} }
@ -376,16 +361,14 @@ export function inbox(inboxFolderName = 'INBOX')
* @param {string=} screenName = '' * @param {string=} screenName = ''
* @returns {string} * @returns {string}
*/ */
export function settings(screenName = '') export function settings(screenName = '') {
{
return HASH_PREFIX + 'settings' + (screenName ? '/' + screenName : ''); return HASH_PREFIX + 'settings' + (screenName ? '/' + screenName : '');
} }
/** /**
* @returns {string} * @returns {string}
*/ */
export function about() export function about() {
{
return HASH_PREFIX + 'about'; return HASH_PREFIX + 'about';
} }
@ -393,11 +376,9 @@ export function about()
* @param {string} screenName * @param {string} screenName
* @returns {string} * @returns {string}
*/ */
export function admin(screenName) export function admin(screenName) {
{
let result = HASH_PREFIX; let result = HASH_PREFIX;
switch (screenName) switch (screenName) {
{
case 'AdminDomains': case 'AdminDomains':
result += 'domains'; result += 'domains';
break; break;
@ -420,28 +401,24 @@ export function admin(screenName)
* @param {string=} threadUid = '' * @param {string=} threadUid = ''
* @returns {string} * @returns {string}
*/ */
export function mailBox(folder, page = 1, search = '', threadUid = '') export function mailBox(folder, page = 1, search = '', threadUid = '') {
{
page = isNormal(page) ? pInt(page) : 1; page = isNormal(page) ? pInt(page) : 1;
search = pString(search); search = pString(search);
let result = HASH_PREFIX + 'mailbox/'; let result = HASH_PREFIX + 'mailbox/';
if ('' !== folder) if ('' !== folder) {
{
const resultThreadUid = pInt(threadUid); const resultThreadUid = pInt(threadUid);
result += window.encodeURI(folder) + (0 < resultThreadUid ? '~' + resultThreadUid : ''); result += window.encodeURI(folder) + (0 < resultThreadUid ? '~' + resultThreadUid : '');
} }
if (1 < page) if (1 < page) {
{ result = result.replace(/[/]+$/, '');
result = result.replace(/[\/]+$/, '');
result += '/p' + page; result += '/p' + page;
} }
if ('' !== search) if ('' !== search) {
{ result = result.replace(/[/]+$/, '');
result = result.replace(/[\/]+$/, '');
result += '/' + window.encodeURI(search); result += '/' + window.encodeURI(search);
} }

View file

@ -1,166 +1,165 @@
/* eslint key-spacing: 0 */ /* eslint key-spacing: 0 */
/* eslint quote-props: 0 */ /* eslint quote-props: 0 */
const Mime = { const Mime = {
'eml' : 'message/rfc822', 'eml': 'message/rfc822',
'mime' : 'message/rfc822', 'mime': 'message/rfc822',
'txt' : 'text/plain', 'txt': 'text/plain',
'text' : 'text/plain', 'text': 'text/plain',
'def' : 'text/plain', 'def': 'text/plain',
'list' : 'text/plain', 'list': 'text/plain',
'in' : 'text/plain', 'in': 'text/plain',
'ini' : 'text/plain', 'ini': 'text/plain',
'log' : 'text/plain', 'log': 'text/plain',
'sql' : 'text/plain', 'sql': 'text/plain',
'cfg' : 'text/plain', 'cfg': 'text/plain',
'conf' : 'text/plain', 'conf': 'text/plain',
'asc' : 'text/plain', 'asc': 'text/plain',
'rtx' : 'text/richtext', 'rtx': 'text/richtext',
'vcard' : 'text/vcard', 'vcard': 'text/vcard',
'vcf' : 'text/vcard', 'vcf': 'text/vcard',
'htm' : 'text/html', 'htm': 'text/html',
'html' : 'text/html', 'html': 'text/html',
'csv' : 'text/csv', 'csv': 'text/csv',
'ics' : 'text/calendar', 'ics': 'text/calendar',
'ifb' : 'text/calendar', 'ifb': 'text/calendar',
'xml' : 'text/xml', 'xml': 'text/xml',
'json' : 'application/json', 'json': 'application/json',
'swf' : 'application/x-shockwave-flash', 'swf': 'application/x-shockwave-flash',
'hlp' : 'application/winhlp', 'hlp': 'application/winhlp',
'wgt' : 'application/widget', 'wgt': 'application/widget',
'chm' : 'application/vnd.ms-htmlhelp', 'chm': 'application/vnd.ms-htmlhelp',
'p10' : 'application/pkcs10', 'p10': 'application/pkcs10',
'p7c' : 'application/pkcs7-mime', 'p7c': 'application/pkcs7-mime',
'p7m' : 'application/pkcs7-mime', 'p7m': 'application/pkcs7-mime',
'p7s' : 'application/pkcs7-signature', 'p7s': 'application/pkcs7-signature',
'torrent' : 'application/x-bittorrent', 'torrent': 'application/x-bittorrent',
// scripts // scripts
'js' : 'application/javascript', 'js': 'application/javascript',
'pl' : 'text/perl', 'pl': 'text/perl',
'css' : 'text/css', 'css': 'text/css',
'asp' : 'text/asp', 'asp': 'text/asp',
'php' : 'application/x-httpd-php', 'php': 'application/x-httpd-php',
'php3' : 'application/x-httpd-php', 'php3': 'application/x-httpd-php',
'php4' : 'application/x-httpd-php', 'php4': 'application/x-httpd-php',
'php5' : 'application/x-httpd-php', 'php5': 'application/x-httpd-php',
'phtml' : 'application/x-httpd-php', 'phtml': 'application/x-httpd-php',
// images // images
'png' : 'image/png', 'png': 'image/png',
'jpg' : 'image/jpeg', 'jpg': 'image/jpeg',
'jpeg' : 'image/jpeg', 'jpeg': 'image/jpeg',
'jpe' : 'image/jpeg', 'jpe': 'image/jpeg',
'jfif' : 'image/jpeg', 'jfif': 'image/jpeg',
'gif' : 'image/gif', 'gif': 'image/gif',
'bmp' : 'image/bmp', 'bmp': 'image/bmp',
'cgm' : 'image/cgm', 'cgm': 'image/cgm',
'ief' : 'image/ief', 'ief': 'image/ief',
'ico' : 'image/x-icon', 'ico': 'image/x-icon',
'tif' : 'image/tiff', 'tif': 'image/tiff',
'tiff' : 'image/tiff', 'tiff': 'image/tiff',
'svg' : 'image/svg+xml', 'svg': 'image/svg+xml',
'svgz' : 'image/svg+xml', 'svgz': 'image/svg+xml',
'djv' : 'image/vnd.djvu', 'djv': 'image/vnd.djvu',
'djvu' : 'image/vnd.djvu', 'djvu': 'image/vnd.djvu',
'webp' : 'image/webp', 'webp': 'image/webp',
// archives // archives
'zip' : 'application/zip', 'zip': 'application/zip',
'7z' : 'application/x-7z-compressed', '7z': 'application/x-7z-compressed',
'rar' : 'application/x-rar-compressed', 'rar': 'application/x-rar-compressed',
'exe' : 'application/x-msdownload', 'exe': 'application/x-msdownload',
'dll' : 'application/x-msdownload', 'dll': 'application/x-msdownload',
'scr' : 'application/x-msdownload', 'scr': 'application/x-msdownload',
'com' : 'application/x-msdownload', 'com': 'application/x-msdownload',
'bat' : 'application/x-msdownload', 'bat': 'application/x-msdownload',
'msi' : 'application/x-msdownload', 'msi': 'application/x-msdownload',
'cab' : 'application/vnd.ms-cab-compressed', 'cab': 'application/vnd.ms-cab-compressed',
'gz' : 'application/x-gzip', 'gz': 'application/x-gzip',
'tgz' : 'application/x-gzip', 'tgz': 'application/x-gzip',
'bz' : 'application/x-bzip', 'bz': 'application/x-bzip',
'bz2' : 'application/x-bzip2', 'bz2': 'application/x-bzip2',
'deb' : 'application/x-debian-package', 'deb': 'application/x-debian-package',
// fonts // fonts
'psf' : 'application/x-font-linux-psf', 'psf': 'application/x-font-linux-psf',
'otf' : 'application/x-font-otf', 'otf': 'application/x-font-otf',
'pcf' : 'application/x-font-pcf', 'pcf': 'application/x-font-pcf',
'snf' : 'application/x-font-snf', 'snf': 'application/x-font-snf',
'ttf' : 'application/x-font-ttf', 'ttf': 'application/x-font-ttf',
'ttc' : 'application/x-font-ttf', 'ttc': 'application/x-font-ttf',
// audio // audio
'mp3' : 'audio/mpeg', 'mp3': 'audio/mpeg',
'amr' : 'audio/amr', 'amr': 'audio/amr',
'aac' : 'audio/x-aac', 'aac': 'audio/x-aac',
'aif' : 'audio/x-aiff', 'aif': 'audio/x-aiff',
'aifc' : 'audio/x-aiff', 'aifc': 'audio/x-aiff',
'aiff' : 'audio/x-aiff', 'aiff': 'audio/x-aiff',
'wav' : 'audio/x-wav', 'wav': 'audio/x-wav',
'wma' : 'audio/x-ms-wma', 'wma': 'audio/x-ms-wma',
'wax' : 'audio/x-ms-wax', 'wax': 'audio/x-ms-wax',
'midi' : 'audio/midi', 'midi': 'audio/midi',
'mp4a' : 'audio/mp4', 'mp4a': 'audio/mp4',
'ogg' : 'audio/ogg', 'ogg': 'audio/ogg',
'weba' : 'audio/webm', 'weba': 'audio/webm',
'ra' : 'audio/x-pn-realaudio', 'ra': 'audio/x-pn-realaudio',
'ram' : 'audio/x-pn-realaudio', 'ram': 'audio/x-pn-realaudio',
'rmp' : 'audio/x-pn-realaudio-plugin', 'rmp': 'audio/x-pn-realaudio-plugin',
'm3u' : 'audio/x-mpegurl', 'm3u': 'audio/x-mpegurl',
// video // video
'flv' : 'video/x-flv', 'flv': 'video/x-flv',
'qt' : 'video/quicktime', 'qt': 'video/quicktime',
'mov' : 'video/quicktime', 'mov': 'video/quicktime',
'wmv' : 'video/windows-media', 'wmv': 'video/windows-media',
'avi' : 'video/x-msvideo', 'avi': 'video/x-msvideo',
'mpg' : 'video/mpeg', 'mpg': 'video/mpeg',
'mpeg' : 'video/mpeg', 'mpeg': 'video/mpeg',
'mpe' : 'video/mpeg', 'mpe': 'video/mpeg',
'm1v' : 'video/mpeg', 'm1v': 'video/mpeg',
'm2v' : 'video/mpeg', 'm2v': 'video/mpeg',
'3gp' : 'video/3gpp', '3gp': 'video/3gpp',
'3g2' : 'video/3gpp2', '3g2': 'video/3gpp2',
'h261' : 'video/h261', 'h261': 'video/h261',
'h263' : 'video/h263', 'h263': 'video/h263',
'h264' : 'video/h264', 'h264': 'video/h264',
'jpgv' : 'video/jpgv', 'jpgv': 'video/jpgv',
'mp4' : 'video/mp4', 'mp4': 'video/mp4',
'mp4v' : 'video/mp4', 'mp4v': 'video/mp4',
'mpg4' : 'video/mp4', 'mpg4': 'video/mp4',
'ogv' : 'video/ogg', 'ogv': 'video/ogg',
'webm' : 'video/webm', 'webm': 'video/webm',
'm4v' : 'video/x-m4v', 'm4v': 'video/x-m4v',
'asf' : 'video/x-ms-asf', 'asf': 'video/x-ms-asf',
'asx' : 'video/x-ms-asf', 'asx': 'video/x-ms-asf',
'wm' : 'video/x-ms-wm', 'wm': 'video/x-ms-wm',
'wmx' : 'video/x-ms-wmx', 'wmx': 'video/x-ms-wmx',
'wvx' : 'video/x-ms-wvx', 'wvx': 'video/x-ms-wvx',
'movie' : 'video/x-sgi-movie', 'movie': 'video/x-sgi-movie',
// adobe // adobe
'pdf' : 'application/pdf', 'pdf': 'application/pdf',
'psd' : 'image/vnd.adobe.photoshop', 'psd': 'image/vnd.adobe.photoshop',
'ai' : 'application/postscript', 'ai': 'application/postscript',
'eps' : 'application/postscript', 'eps': 'application/postscript',
'ps' : 'application/postscript', 'ps': 'application/postscript',
// ms office // ms office
'doc' : 'application/msword', 'doc': 'application/msword',
'dot' : 'application/msword', 'dot': 'application/msword',
'rtf' : 'application/rtf', 'rtf': 'application/rtf',
'xls' : 'application/vnd.ms-excel', 'xls': 'application/vnd.ms-excel',
'ppt' : 'application/vnd.ms-powerpoint', 'ppt': 'application/vnd.ms-powerpoint',
'docx' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xlsx' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'dotx' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'dotx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'pptx' : 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
// open office // open office
'odt' : 'application/vnd.oasis.opendocument.text', 'odt': 'application/vnd.oasis.opendocument.text',
'ods' : 'application/vnd.oasis.opendocument.spreadsheet' 'ods': 'application/vnd.oasis.opendocument.spreadsheet'
}; };
export {Mime, Mime as default}; export { Mime, Mime as default };

View file

@ -1,26 +1,32 @@
import window from 'window'; import window from 'window';
import _ from '_'; import _ from '_';
import $ from '$'; import $ from '$';
import moment from 'moment'; import moment from 'moment';
import {i18n} from 'Common/Translator'; import { i18n } from 'Common/Translator';
let _moment = null; let _moment = null;
let _momentNow = 0; let _momentNow = 0;
const updateMomentNow = _.debounce(() => { const updateMomentNow = _.debounce(
_moment = moment(); () => {
}, 500, true); _moment = moment();
},
500,
true
);
const updateMomentNowUnix = _.debounce(() => { const updateMomentNowUnix = _.debounce(
_momentNow = moment().unix(); () => {
}, 500, true); _momentNow = moment().unix();
},
500,
true
);
/** /**
* @returns {moment} * @returns {moment}
*/ */
export function momentNow() export function momentNow() {
{
updateMomentNow(); updateMomentNow();
return _moment || moment(); return _moment || moment();
} }
@ -28,8 +34,7 @@ export function momentNow()
/** /**
* @returns {number} * @returns {number}
*/ */
export function momentNowUnix() export function momentNowUnix() {
{
updateMomentNowUnix(); updateMomentNowUnix();
return _momentNow || 0; return _momentNow || 0;
} }
@ -38,29 +43,31 @@ export function momentNowUnix()
* @param {number} date * @param {number} date
* @returns {string} * @returns {string}
*/ */
export function searchSubtractFormatDateHelper(date) export function searchSubtractFormatDateHelper(date) {
{ return momentNow()
return momentNow().clone().subtract(date, 'days').format('YYYY.MM.DD'); .clone()
.subtract(date, 'days')
.format('YYYY.MM.DD');
} }
/** /**
* @param {Object} m * @param {Object} m
* @returns {string} * @returns {string}
*/ */
function formatCustomShortDate(m) function formatCustomShortDate(m) {
{
const now = momentNow(); const now = momentNow();
if (m && now) if (m && now) {
{ switch (true) {
switch (true)
{
case 4 >= now.diff(m, 'hours'): case 4 >= now.diff(m, 'hours'):
return m.fromNow(); return m.fromNow();
case now.format('L') === m.format('L'): case now.format('L') === m.format('L'):
return i18n('MESSAGE_LIST/TODAY_AT', { return i18n('MESSAGE_LIST/TODAY_AT', {
TIME: m.format('LT') TIME: m.format('LT')
}); });
case now.clone().subtract(1, 'days').format('L') === m.format('L'): case now
.clone()
.subtract(1, 'days')
.format('L') === m.format('L'):
return i18n('MESSAGE_LIST/YESTERDAY_AT', { return i18n('MESSAGE_LIST/YESTERDAY_AT', {
TIME: m.format('LT') TIME: m.format('LT')
}); });
@ -78,29 +85,23 @@ function formatCustomShortDate(m)
* @param {string} formatStr * @param {string} formatStr
* @returns {string} * @returns {string}
*/ */
export function format(timeStampInUTC, formatStr) export function format(timeStampInUTC, formatStr) {
{ let m = null,
let
m = null,
result = ''; result = '';
const now = momentNowUnix(); const now = momentNowUnix();
timeStampInUTC = 0 < timeStampInUTC ? timeStampInUTC : (0 === timeStampInUTC ? now : 0); timeStampInUTC = 0 < timeStampInUTC ? timeStampInUTC : 0 === timeStampInUTC ? now : 0;
timeStampInUTC = now < timeStampInUTC ? now : timeStampInUTC; timeStampInUTC = now < timeStampInUTC ? now : timeStampInUTC;
m = 0 < timeStampInUTC ? moment.unix(timeStampInUTC) : null; m = 0 < timeStampInUTC ? moment.unix(timeStampInUTC) : null;
if (m && 1970 === m.year()) if (m && 1970 === m.year()) {
{
m = null; m = null;
} }
if (m) if (m) {
{ switch (formatStr) {
switch (formatStr)
{
case 'FROMNOW': case 'FROMNOW':
result = m.fromNow(); result = m.fromNow();
break; break;
@ -123,26 +124,20 @@ export function format(timeStampInUTC, formatStr)
* @param {Object} element * @param {Object} element
* @returns {void} * @returns {void}
*/ */
export function momentToNode(element) export function momentToNode(element) {
{ let key = '',
let
key = '',
time = 0; time = 0;
const const $el = $(element);
$el = $(element);
time = $el.data('moment-time'); time = $el.data('moment-time');
if (time) if (time) {
{
key = $el.data('moment-format'); key = $el.data('moment-format');
if (key) if (key) {
{
$el.text(format(time, key)); $el.text(format(time, key));
} }
key = $el.data('moment-format-title'); key = $el.data('moment-format-title');
if (key) if (key) {
{
$el.attr('title', format(time, key)); $el.attr('title', format(time, key));
} }
} }
@ -151,8 +146,7 @@ export function momentToNode(element)
/** /**
* @returns {void} * @returns {void}
*/ */
export function reload() export function reload() {
{
_.defer(() => { _.defer(() => {
$('.moment', window.document).each((index, item) => { $('.moment', window.document).each((index, item) => {
momentToNode(item); momentToNode(item);

View file

@ -1,11 +1,9 @@
import _ from '_'; import _ from '_';
import {isFunc, isArray, isUnd} from 'Common/Utils'; import { isFunc, isArray, isUnd } from 'Common/Utils';
import {data as GlobalsData} from 'Common/Globals'; import { data as GlobalsData } from 'Common/Globals';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
const const SIMPLE_HOOKS = {},
SIMPLE_HOOKS = {},
USER_VIEW_MODELS_HOOKS = [], USER_VIEW_MODELS_HOOKS = [],
ADMIN_VIEW_MODELS_HOOKS = []; ADMIN_VIEW_MODELS_HOOKS = [];
@ -13,12 +11,9 @@ const
* @param {string} name * @param {string} name
* @param {Function} callback * @param {Function} callback
*/ */
export function addHook(name, callback) export function addHook(name, callback) {
{ if (isFunc(callback)) {
if (isFunc(callback)) if (!isArray(SIMPLE_HOOKS[name])) {
{
if (!isArray(SIMPLE_HOOKS[name]))
{
SIMPLE_HOOKS[name] = []; SIMPLE_HOOKS[name] = [];
} }
@ -30,10 +25,8 @@ export function addHook(name, callback)
* @param {string} name * @param {string} name
* @param {Array=} args = [] * @param {Array=} args = []
*/ */
export function runHook(name, args = []) export function runHook(name, args = []) {
{ if (isArray(SIMPLE_HOOKS[name])) {
if (isArray(SIMPLE_HOOKS[name]))
{
_.each(SIMPLE_HOOKS[name], (callback) => { _.each(SIMPLE_HOOKS[name], (callback) => {
callback(...args); callback(...args);
}); });
@ -44,8 +37,7 @@ export function runHook(name, args = [])
* @param {string} name * @param {string} name
* @returns {?} * @returns {?}
*/ */
export function mainSettingsGet(name) export function mainSettingsGet(name) {
{
return Settings.settingsGet(name); return Settings.settingsGet(name);
} }
@ -55,10 +47,8 @@ export function mainSettingsGet(name)
* @param {Object=} parameters * @param {Object=} parameters
* @param {?number=} timeout * @param {?number=} timeout
*/ */
export function remoteRequest(callback, action, parameters, timeout) export function remoteRequest(callback, action, parameters, timeout) {
{ if (GlobalsData.__APP__) {
if (GlobalsData.__APP__)
{
GlobalsData.__APP__.remote().defaultRequest(callback, 'Plugin' + action, parameters, timeout); GlobalsData.__APP__.remote().defaultRequest(callback, 'Plugin' + action, parameters, timeout);
} }
} }
@ -69,8 +59,7 @@ export function remoteRequest(callback, action, parameters, timeout)
* @param {string} template * @param {string} template
* @param {string} route * @param {string} route
*/ */
export function addSettingsViewModel(SettingsViewModelClass, template, labelName, route) export function addSettingsViewModel(SettingsViewModelClass, template, labelName, route) {
{
USER_VIEW_MODELS_HOOKS.push([SettingsViewModelClass, template, labelName, route]); USER_VIEW_MODELS_HOOKS.push([SettingsViewModelClass, template, labelName, route]);
} }
@ -80,16 +69,14 @@ export function addSettingsViewModel(SettingsViewModelClass, template, labelName
* @param {string} template * @param {string} template
* @param {string} route * @param {string} route
*/ */
export function addSettingsViewModelForAdmin(SettingsViewModelClass, template, labelName, route) export function addSettingsViewModelForAdmin(SettingsViewModelClass, template, labelName, route) {
{
ADMIN_VIEW_MODELS_HOOKS.push([SettingsViewModelClass, template, labelName, route]); ADMIN_VIEW_MODELS_HOOKS.push([SettingsViewModelClass, template, labelName, route]);
} }
/** /**
* @param {boolean} admin * @param {boolean} admin
*/ */
export function runSettingsViewModelHooks(admin) export function runSettingsViewModelHooks(admin) {
{
const Knoin = require('Knoin/Knoin'); const Knoin = require('Knoin/Knoin');
_.each(admin ? ADMIN_VIEW_MODELS_HOOKS : USER_VIEW_MODELS_HOOKS, (view) => { _.each(admin ? ADMIN_VIEW_MODELS_HOOKS : USER_VIEW_MODELS_HOOKS, (view) => {
Knoin.addSettingsViewModel(view[0], view[1], view[2], view[3]); Knoin.addSettingsViewModel(view[0], view[1], view[2], view[3]);
@ -101,8 +88,7 @@ export function runSettingsViewModelHooks(admin)
* @param {string} name * @param {string} name
* @returns {?} * @returns {?}
*/ */
export function settingsGet(pluginSection, name) export function settingsGet(pluginSection, name) {
{
let plugins = Settings.settingsGet('Plugins'); let plugins = Settings.settingsGet('Plugins');
plugins = plugins && !isUnd(plugins[pluginSection]) ? plugins[pluginSection] : null; plugins = plugins && !isUnd(plugins[pluginSection]) ? plugins[pluginSection] : null;
return plugins ? (isUnd(plugins[name]) ? null : plugins[name]) : null; return plugins ? (isUnd(plugins[name]) ? null : plugins[name]) : null;

View file

@ -1,13 +1,11 @@
import $ from '$'; import $ from '$';
import _ from '_'; import _ from '_';
import key from 'key'; import key from 'key';
import ko from 'ko'; import ko from 'ko';
import {EventKeyCode} from 'Common/Enums'; import { EventKeyCode } from 'Common/Enums';
import {isArray, inArray, noop, noopTrue} from 'Common/Utils'; import { isArray, inArray, noop, noopTrue } from 'Common/Utils';
class Selector class Selector {
{
list; list;
listChecked; listChecked;
isListChecked; isListChecked;
@ -41,12 +39,18 @@ class Selector
* @param {string} sItemCheckedSelector * @param {string} sItemCheckedSelector
* @param {string} sItemFocusedSelector * @param {string} sItemFocusedSelector
*/ */
constructor(koList, koSelectedItem, koFocusedItem, constructor(
sItemSelector, sItemSelectedSelector, sItemCheckedSelector, sItemFocusedSelector) koList,
{ koSelectedItem,
koFocusedItem,
sItemSelector,
sItemSelectedSelector,
sItemCheckedSelector,
sItemFocusedSelector
) {
this.list = koList; this.list = koList;
this.listChecked = ko.computed(() => _.filter(this.list(), (item) => item.checked())).extend({rateLimit: 0}); this.listChecked = ko.computed(() => _.filter(this.list(), (item) => item.checked())).extend({ rateLimit: 0 });
this.isListChecked = ko.computed(() => 0 < this.listChecked().length); this.isListChecked = ko.computed(() => 0 < this.listChecked().length);
this.focusedItem = koFocusedItem || ko.observable(null); this.focusedItem = koFocusedItem || ko.observable(null);
@ -55,51 +59,37 @@ class Selector
this.itemSelectedThrottle = _.debounce(_.bind(this.itemSelected, this), 300); this.itemSelectedThrottle = _.debounce(_.bind(this.itemSelected, this), 300);
this.listChecked.subscribe((items) => { this.listChecked.subscribe((items) => {
if (0 < items.length) if (0 < items.length) {
{ if (null === this.selectedItem()) {
if (null === this.selectedItem()) if (this.selectedItem.valueHasMutated) {
{
if (this.selectedItem.valueHasMutated)
{
this.selectedItem.valueHasMutated(); this.selectedItem.valueHasMutated();
} }
} } else {
else
{
this.selectedItem(null); this.selectedItem(null);
} }
} } else if (this.autoSelect() && this.focusedItem()) {
else if (this.autoSelect() && this.focusedItem())
{
this.selectedItem(this.focusedItem()); this.selectedItem(this.focusedItem());
} }
}, this); }, this);
this.selectedItem.subscribe((item) => { this.selectedItem.subscribe((item) => {
if (item) {
if (item) if (this.isListChecked()) {
{
if (this.isListChecked())
{
_.each(this.listChecked(), (subItem) => { _.each(this.listChecked(), (subItem) => {
subItem.checked(false); subItem.checked(false);
}); });
} }
if (this.selectedItemUseCallback) if (this.selectedItemUseCallback) {
{
this.itemSelectedThrottle(item); this.itemSelectedThrottle(item);
} }
} } else if (this.selectedItemUseCallback) {
else if (this.selectedItemUseCallback)
{
this.itemSelected(null); this.itemSelected(null);
} }
}, this); }, this);
this.selectedItem = this.selectedItem.extend({toggleSubscribeProperty: [this, 'selected']}); this.selectedItem = this.selectedItem.extend({ toggleSubscribeProperty: [this, 'selected'] });
this.focusedItem = this.focusedItem.extend({toggleSubscribeProperty: [null, 'focused']}); this.focusedItem = this.focusedItem.extend({ toggleSubscribeProperty: [null, 'focused'] });
this.sItemSelector = sItemSelector; this.sItemSelector = sItemSelector;
this.sItemSelectedSelector = sItemSelectedSelector; this.sItemSelectedSelector = sItemSelectedSelector;
@ -107,87 +97,75 @@ class Selector
this.sItemFocusedSelector = sItemFocusedSelector; this.sItemFocusedSelector = sItemFocusedSelector;
this.focusedItem.subscribe((item) => { this.focusedItem.subscribe((item) => {
if (item) if (item) {
{
this.sLastUid = this.getItemUid(item); this.sLastUid = this.getItemUid(item);
} }
}, this); }, this);
let let aCache = [],
aCache = [],
aCheckedCache = [], aCheckedCache = [],
mFocused = null, mFocused = null,
mSelected = null; mSelected = null;
this.list.subscribe((items) => { this.list.subscribe(
(items) => {
if (isArray(items)) {
_.each(items, (item) => {
if (item) {
const uid = this.getItemUid(item);
if (isArray(items)) aCache.push(uid);
{ if (item.checked()) {
_.each(items, (item) => { aCheckedCache.push(uid);
if (item) }
{ if (null === mFocused && item.focused()) {
const uid = this.getItemUid(item); mFocused = uid;
}
aCache.push(uid); if (null === mSelected && item.selected()) {
if (item.checked()) mSelected = uid;
{ }
aCheckedCache.push(uid);
} }
if (null === mFocused && item.focused()) });
{ }
mFocused = uid; },
} this,
if (null === mSelected && item.selected()) 'beforeChange'
{ );
mSelected = uid;
}
}
});
}
}, this, 'beforeChange');
this.list.subscribe((aItems) => { this.list.subscribe((aItems) => {
let temp = null,
let
temp = null,
getNext = false, getNext = false,
isNextFocused = mFocused, isNextFocused = mFocused,
isChecked = false, isChecked = false,
isSelected = false, isSelected = false,
len = 0; len = 0;
const const uids = [];
uids = [];
this.selectedItemUseCallback = false; this.selectedItemUseCallback = false;
this.focusedItem(null); this.focusedItem(null);
this.selectedItem(null); this.selectedItem(null);
if (isArray(aItems)) if (isArray(aItems)) {
{
len = aCheckedCache.length; len = aCheckedCache.length;
_.each(aItems, (item) => { _.each(aItems, (item) => {
const uid = this.getItemUid(item); const uid = this.getItemUid(item);
uids.push(uid); uids.push(uid);
if (null !== mFocused && mFocused === uid) if (null !== mFocused && mFocused === uid) {
{
this.focusedItem(item); this.focusedItem(item);
mFocused = null; mFocused = null;
} }
if (0 < len && -1 < inArray(uid, aCheckedCache)) if (0 < len && -1 < inArray(uid, aCheckedCache)) {
{
isChecked = true; isChecked = true;
item.checked(true); item.checked(true);
len -= 1; len -= 1;
} }
if (!isChecked && null !== mSelected && mSelected === uid) if (!isChecked && null !== mSelected && mSelected === uid) {
{
isSelected = true; isSelected = true;
this.selectedItem(item); this.selectedItem(item);
mSelected = null; mSelected = null;
@ -196,31 +174,22 @@ class Selector
this.selectedItemUseCallback = true; this.selectedItemUseCallback = true;
if (!isChecked && !isSelected && this.autoSelect()) if (!isChecked && !isSelected && this.autoSelect()) {
{ if (this.focusedItem()) {
if (this.focusedItem())
{
this.selectedItem(this.focusedItem()); this.selectedItem(this.focusedItem());
} } else if (0 < aItems.length) {
else if (0 < aItems.length) if (null !== isNextFocused) {
{
if (null !== isNextFocused)
{
getNext = false; getNext = false;
isNextFocused = _.find(aCache, (sUid) => { isNextFocused = _.find(aCache, (sUid) => {
if (getNext && -1 < inArray(sUid, uids)) if (getNext && -1 < inArray(sUid, uids)) {
{
return sUid; return sUid;
} } else if (isNextFocused === sUid) {
else if (isNextFocused === sUid)
{
getNext = true; getNext = true;
} }
return false; return false;
}); });
if (isNextFocused) if (isNextFocused) {
{
temp = _.find(aItems, (oItem) => isNextFocused === this.getItemUid(oItem)); temp = _.find(aItems, (oItem) => isNextFocused === this.getItemUid(oItem));
} }
} }
@ -230,23 +199,22 @@ class Selector
} }
} }
if ((0 !== this.iSelectNextHelper || 0 !== this.iFocusedNextHelper) && 0 < aItems.length && !this.focusedItem()) if (
{ (0 !== this.iSelectNextHelper || 0 !== this.iFocusedNextHelper) &&
0 < aItems.length &&
!this.focusedItem()
) {
temp = null; temp = null;
if (0 !== this.iFocusedNextHelper) if (0 !== this.iFocusedNextHelper) {
{
temp = aItems[-1 === this.iFocusedNextHelper ? aItems.length - 1 : 0] || null; temp = aItems[-1 === this.iFocusedNextHelper ? aItems.length - 1 : 0] || null;
} }
if (!temp && 0 !== this.iSelectNextHelper) if (!temp && 0 !== this.iSelectNextHelper) {
{
temp = aItems[-1 === this.iSelectNextHelper ? aItems.length - 1 : 0] || null; temp = aItems[-1 === this.iSelectNextHelper ? aItems.length - 1 : 0] || null;
} }
if (temp) if (temp) {
{ if (0 !== this.iSelectNextHelper) {
if (0 !== this.iSelectNextHelper)
{
this.selectedItem(temp || null); this.selectedItem(temp || null);
} }
@ -266,21 +234,15 @@ class Selector
aCheckedCache = []; aCheckedCache = [];
mFocused = null; mFocused = null;
mSelected = null; mSelected = null;
}); });
} }
itemSelected(item) { itemSelected(item) {
if (this.isListChecked()) {
if (this.isListChecked()) if (!item) {
{
if (!item)
{
(this.oCallbacks.onItemSelect || noop)(item || null); (this.oCallbacks.onItemSelect || noop)(item || null);
} }
} } else if (item) {
else if (item)
{
(this.oCallbacks.onItemSelect || noop)(item); (this.oCallbacks.onItemSelect || noop)(item);
} }
} }
@ -305,16 +267,13 @@ class Selector
} }
init(contentVisible, contentScrollable, keyScope = 'all') { init(contentVisible, contentScrollable, keyScope = 'all') {
this.oContentVisible = contentVisible; this.oContentVisible = contentVisible;
this.oContentScrollable = contentScrollable; this.oContentScrollable = contentScrollable;
if (this.oContentVisible && this.oContentScrollable) if (this.oContentVisible && this.oContentScrollable) {
{
$(this.oContentVisible) $(this.oContentVisible)
.on('selectstart', (event) => { .on('selectstart', (event) => {
if (event && event.preventDefault) if (event && event.preventDefault) {
{
event.preventDefault(); event.preventDefault();
} }
}) })
@ -323,14 +282,10 @@ class Selector
}) })
.on('click', this.sItemCheckedSelector, (event) => { .on('click', this.sItemCheckedSelector, (event) => {
const item = ko.dataFor(event.currentTarget); const item = ko.dataFor(event.currentTarget);
if (item) if (item) {
{ if (event && event.shiftKey) {
if (event && event.shiftKey)
{
this.actionClick(item, event); this.actionClick(item, event);
} } else {
else
{
this.focusedItem(item); this.focusedItem(item);
item.checked(!item.checked()); item.checked(!item.checked());
} }
@ -338,8 +293,7 @@ class Selector
}); });
key('enter', keyScope, () => { key('enter', keyScope, () => {
if (this.focusedItem() && !this.focusedItem().selected()) if (this.focusedItem() && !this.focusedItem().selected()) {
{
this.actionClick(this.focusedItem()); this.actionClick(this.focusedItem());
return false; return false;
} }
@ -350,11 +304,9 @@ class Selector
key('ctrl+up, command+up, ctrl+down, command+down', keyScope, () => false); 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) => { key('up, shift+up, down, shift+down, home, end, pageup, pagedown, insert, space', keyScope, (event, handler) => {
if (event && handler && handler.shortcut) if (event && handler && handler.shortcut) {
{
let eventKey = 0; let eventKey = 0;
switch (handler.shortcut) switch (handler.shortcut) {
{
case 'up': case 'up':
case 'shift+up': case 'shift+up':
eventKey = EventKeyCode.Up; eventKey = EventKeyCode.Up;
@ -384,8 +336,7 @@ class Selector
// no default // no default
} }
if (0 < eventKey) if (0 < eventKey) {
{
this.newSelectPosition(eventKey, key.shift); this.newSelectPosition(eventKey, key.shift);
return false; return false;
} }
@ -415,12 +366,10 @@ class Selector
* @returns {string} * @returns {string}
*/ */
getItemUid(item) { getItemUid(item) {
let uid = ''; let uid = '';
const getItemUidCallback = this.oCallbacks.onItemGetUid || null; const getItemUidCallback = this.oCallbacks.onItemGetUid || null;
if (getItemUidCallback && item) if (getItemUidCallback && item) {
{
uid = getItemUidCallback(item); uid = getItemUidCallback(item);
} }
@ -433,64 +382,56 @@ class Selector
* @param {boolean=} bForceSelect = false * @param {boolean=} bForceSelect = false
*/ */
newSelectPosition(iEventKeyCode, bShiftKey, bForceSelect) { newSelectPosition(iEventKeyCode, bShiftKey, bForceSelect) {
let index = 0,
let
index = 0,
isNext = false, isNext = false,
isStop = false, isStop = false,
result = null; result = null;
const const pageStep = 10,
pageStep = 10,
list = this.list(), list = this.list(),
listLen = list ? list.length : 0, listLen = list ? list.length : 0,
focused = this.focusedItem(); focused = this.focusedItem();
if (0 < listLen) if (0 < listLen) {
{ if (!focused) {
if (!focused) if (
{ EventKeyCode.Down === iEventKeyCode ||
if (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Insert === iEventKeyCode ||
EventKeyCode.Space === iEventKeyCode || EventKeyCode.Home === iEventKeyCode || EventKeyCode.Space === iEventKeyCode ||
EventKeyCode.PageUp === iEventKeyCode) EventKeyCode.Home === iEventKeyCode ||
{ EventKeyCode.PageUp === iEventKeyCode
) {
result = list[0]; result = list[0];
} } else if (
else if (EventKeyCode.Up === iEventKeyCode || EventKeyCode.End === iEventKeyCode || EventKeyCode.Up === iEventKeyCode ||
EventKeyCode.PageDown === iEventKeyCode) EventKeyCode.End === iEventKeyCode ||
{ EventKeyCode.PageDown === iEventKeyCode
) {
result = list[list.length - 1]; result = list[list.length - 1];
} }
} } else if (focused) {
else if (focused) if (
{ EventKeyCode.Down === iEventKeyCode ||
if (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Up === iEventKeyCode || EventKeyCode.Up === iEventKeyCode ||
EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode) EventKeyCode.Insert === iEventKeyCode ||
{ EventKeyCode.Space === iEventKeyCode
) {
_.each(list, (item) => { _.each(list, (item) => {
if (!isStop) if (!isStop) {
{ switch (iEventKeyCode) {
switch (iEventKeyCode)
{
case EventKeyCode.Up: case EventKeyCode.Up:
if (focused === item) if (focused === item) {
{
isStop = true; isStop = true;
} } else {
else
{
result = item; result = item;
} }
break; break;
case EventKeyCode.Down: case EventKeyCode.Down:
case EventKeyCode.Insert: case EventKeyCode.Insert:
if (isNext) if (isNext) {
{
result = item; result = item;
isStop = true; isStop = true;
} } else if (focused === item) {
else if (focused === item)
{
isNext = true; isNext = true;
} }
break; break;
@ -499,41 +440,27 @@ class Selector
} }
}); });
if (!result && (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Up === iEventKeyCode)) if (!result && (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Up === iEventKeyCode)) {
{
this.doUpUpOrDownDown(EventKeyCode.Up === iEventKeyCode); this.doUpUpOrDownDown(EventKeyCode.Up === iEventKeyCode);
} }
} } else if (EventKeyCode.Home === iEventKeyCode || EventKeyCode.End === iEventKeyCode) {
else if (EventKeyCode.Home === iEventKeyCode || EventKeyCode.End === iEventKeyCode) if (EventKeyCode.Home === iEventKeyCode) {
{
if (EventKeyCode.Home === iEventKeyCode)
{
result = list[0]; result = list[0];
} } else if (EventKeyCode.End === iEventKeyCode) {
else if (EventKeyCode.End === iEventKeyCode)
{
result = list[list.length - 1]; result = list[list.length - 1];
} }
} } else if (EventKeyCode.PageDown === iEventKeyCode) {
else if (EventKeyCode.PageDown === iEventKeyCode) for (; index < listLen; index++) {
{ if (focused === list[index]) {
for (; index < listLen; index++)
{
if (focused === list[index])
{
index += pageStep; index += pageStep;
index = listLen - 1 < index ? listLen - 1 : index; index = listLen - 1 < index ? listLen - 1 : index;
result = list[index]; result = list[index];
break; break;
} }
} }
} } else if (EventKeyCode.PageUp === iEventKeyCode) {
else if (EventKeyCode.PageUp === iEventKeyCode) for (index = listLen; 0 <= index; index--) {
{ if (focused === list[index]) {
for (index = listLen; 0 <= index; index--)
{
if (focused === list[index])
{
index -= pageStep; index -= pageStep;
index = 0 > index ? 0 : index; index = 0 > index ? 0 : index;
result = list[index]; result = list[index];
@ -544,41 +471,28 @@ class Selector
} }
} }
if (result) if (result) {
{
this.focusedItem(result); this.focusedItem(result);
if (focused) if (focused) {
{ if (bShiftKey) {
if (bShiftKey) if (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode) {
{
if (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode)
{
focused.checked(!focused.checked()); focused.checked(!focused.checked());
} }
} } else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode) {
else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode)
{
focused.checked(!focused.checked()); focused.checked(!focused.checked());
} }
} }
if ((this.autoSelect() || !!bForceSelect) && if ((this.autoSelect() || !!bForceSelect) && !this.isListChecked() && EventKeyCode.Space !== iEventKeyCode) {
!this.isListChecked() && EventKeyCode.Space !== iEventKeyCode)
{
this.selectedItem(result); this.selectedItem(result);
} }
this.scrollToFocused(); this.scrollToFocused();
} } else if (focused) {
else if (focused) if (bShiftKey && (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode)) {
{
if (bShiftKey && (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode))
{
focused.checked(!focused.checked()); focused.checked(!focused.checked());
} } else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode) {
else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode)
{
focused.checked(!focused.checked()); focused.checked(!focused.checked());
} }
@ -590,30 +504,25 @@ class Selector
* @returns {boolean} * @returns {boolean}
*/ */
scrollToFocused() { scrollToFocused() {
if (!this.oContentVisible || !this.oContentScrollable) {
if (!this.oContentVisible || !this.oContentScrollable)
{
return false; return false;
} }
const const offset = 20,
offset = 20,
list = this.list(), list = this.list(),
$focused = $(this.sItemFocusedSelector, this.oContentScrollable), $focused = $(this.sItemFocusedSelector, this.oContentScrollable),
pos = $focused.position(), pos = $focused.position(),
visibleHeight = this.oContentVisible.height(), visibleHeight = this.oContentVisible.height(),
focusedHeight = $focused.outerHeight(); focusedHeight = $focused.outerHeight();
if (list && list[0] && list[0].focused()) if (list && list[0] && list[0].focused()) {
{
this.oContentScrollable.scrollTop(0); this.oContentScrollable.scrollTop(0);
return true; return true;
} } else if (pos && (0 > pos.top || pos.top + focusedHeight > visibleHeight)) {
else if (pos && (0 > pos.top || pos.top + focusedHeight > visibleHeight)) this.oContentScrollable.scrollTop(
{ 0 > pos.top
this.oContentScrollable.scrollTop(0 > pos.top ? ? this.oContentScrollable.scrollTop() + pos.top - offset
this.oContentScrollable.scrollTop() + pos.top - offset : : this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset
this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset
); );
return true; return true;
@ -627,28 +536,21 @@ class Selector
* @returns {boolean} * @returns {boolean}
*/ */
scrollToTop(fast = false) { scrollToTop(fast = false) {
if (!this.oContentVisible || !this.oContentScrollable) {
if (!this.oContentVisible || !this.oContentScrollable)
{
return false; return false;
} }
if (fast || 50 > this.oContentScrollable.scrollTop()) if (fast || 50 > this.oContentScrollable.scrollTop()) {
{
this.oContentScrollable.scrollTop(0); this.oContentScrollable.scrollTop(0);
} } else {
else this.oContentScrollable.stop().animate({ scrollTop: 0 }, 200);
{
this.oContentScrollable.stop().animate({scrollTop: 0}, 200);
} }
return true; return true;
} }
eventClickFunction(item, event) { eventClickFunction(item, event) {
let index = 0,
let
index = 0,
length = 0, length = 0,
changeRange = false, changeRange = false,
isInRange = false, isInRange = false,
@ -658,31 +560,25 @@ class Selector
lineUid = ''; lineUid = '';
const uid = this.getItemUid(item); const uid = this.getItemUid(item);
if (event && event.shiftKey) if (event && event.shiftKey) {
{ if ('' !== uid && '' !== this.sLastUid && uid !== this.sLastUid) {
if ('' !== uid && '' !== this.sLastUid && uid !== this.sLastUid)
{
list = this.list(); list = this.list();
checked = item.checked(); checked = item.checked();
for (index = 0, length = list.length; index < length; index++) for (index = 0, length = list.length; index < length; index++) {
{
listItem = list[index]; listItem = list[index];
lineUid = this.getItemUid(listItem); lineUid = this.getItemUid(listItem);
changeRange = false; changeRange = false;
if (lineUid === this.sLastUid || lineUid === uid) if (lineUid === this.sLastUid || lineUid === uid) {
{
changeRange = true; changeRange = true;
} }
if (changeRange) if (changeRange) {
{
isInRange = !isInRange; isInRange = !isInRange;
} }
if (isInRange || changeRange) if (isInRange || changeRange) {
{
listItem.checked(checked); listItem.checked(checked);
} }
} }
@ -697,17 +593,12 @@ class Selector
* @param {Object=} event * @param {Object=} event
*/ */
actionClick(item, event = null) { actionClick(item, event = null) {
if (item) {
if (item)
{
let click = true; let click = true;
if (event) if (event) {
{ if (event.shiftKey && !(event.ctrlKey || event.metaKey) && !event.altKey) {
if (event.shiftKey && !(event.ctrlKey || event.metaKey) && !event.altKey)
{
click = false; click = false;
if ('' === this.sLastUid) if ('' === this.sLastUid) {
{
this.sLastUid = this.getItemUid(item); this.sLastUid = this.getItemUid(item);
} }
@ -715,14 +606,11 @@ class Selector
this.eventClickFunction(item, event); this.eventClickFunction(item, event);
this.focusedItem(item); this.focusedItem(item);
} } else if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
else if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey)
{
click = false; click = false;
this.focusedItem(item); this.focusedItem(item);
if (this.selectedItem() && item !== this.selectedItem()) if (this.selectedItem() && item !== this.selectedItem()) {
{
this.selectedItem().checked(true); this.selectedItem().checked(true);
} }
@ -730,8 +618,7 @@ class Selector
} }
} }
if (click) if (click) {
{
this.selectMessageItem(item); this.selectMessageItem(item);
} }
} }
@ -748,4 +635,4 @@ class Selector
} }
} }
export {Selector, Selector as default}; export { Selector, Selector as default };

View file

@ -1,13 +1,12 @@
import window from 'window'; import window from 'window';
import _ from '_'; import _ from '_';
import $ from '$'; import $ from '$';
import ko from 'ko'; import ko from 'ko';
import {Notification, UploadErrorCode} from 'Common/Enums'; import { Notification, UploadErrorCode } from 'Common/Enums';
import {pInt, isUnd, isNull, has, microtime, inArray} from 'Common/Utils'; import { pInt, isUnd, isNull, has, microtime, inArray } from 'Common/Utils';
import {$html, bAnimationSupported} from 'Common/Globals'; import { $html, bAnimationSupported } from 'Common/Globals';
import {reload as momentorReload} from 'Common/Momentor'; import { reload as momentorReload } from 'Common/Momentor';
import {langLink} from 'Common/Links'; import { langLink } from 'Common/Links';
let I18N_DATA = window.rainloopI18N || {}; let I18N_DATA = window.rainloopI18N || {};
@ -91,23 +90,17 @@ export const trigger = ko.observable(false);
* @param {string=} defaulValue * @param {string=} defaulValue
* @returns {string} * @returns {string}
*/ */
export function i18n(key, valueList, defaulValue) export function i18n(key, valueList, defaulValue) {
{ let valueName = '',
let
valueName = '',
result = I18N_DATA[key]; result = I18N_DATA[key];
if (isUnd(result)) if (isUnd(result)) {
{
result = isUnd(defaulValue) ? key : defaulValue; result = isUnd(defaulValue) ? key : defaulValue;
} }
if (!isUnd(valueList) && !isNull(valueList)) if (!isUnd(valueList) && !isNull(valueList)) {
{ for (valueName in valueList) {
for (valueName in valueList) if (has(valueList, valueName)) {
{
if (has(valueList, valueName))
{
result = result.replace('%' + valueName + '%', valueList[valueName]); result = result.replace('%' + valueName + '%', valueList[valueName]);
} }
} }
@ -117,17 +110,12 @@ export function i18n(key, valueList, defaulValue)
} }
const i18nToNode = (element) => { const i18nToNode = (element) => {
const $el = $(element),
const
$el = $(element),
key = $el.data('i18n'); key = $el.data('i18n');
if (key) if (key) {
{ if ('[' === key.substr(0, 1)) {
if ('[' === key.substr(0, 1)) switch (key.substr(0, 6)) {
{
switch (key.substr(0, 6))
{
case '[html]': case '[html]':
$el.html(i18n(key.substr(6))); $el.html(i18n(key.substr(6)));
break; break;
@ -139,9 +127,7 @@ const i18nToNode = (element) => {
break; break;
// no default // no default
} }
} } else {
else
{
$el.text(i18n(key)); $el.text(i18n(key));
} }
} }
@ -151,16 +137,13 @@ const i18nToNode = (element) => {
* @param {Object} elements * @param {Object} elements
* @param {boolean=} animate = false * @param {boolean=} animate = false
*/ */
export function i18nToNodes(elements, animate = false) export function i18nToNodes(elements, animate = false) {
{
_.defer(() => { _.defer(() => {
$('[data-i18n]', elements).each((index, item) => { $('[data-i18n]', elements).each((index, item) => {
i18nToNode(item); i18nToNode(item);
}); });
if (animate && bAnimationSupported) if (animate && bAnimationSupported) {
{
$('.i18n-animation[data-i18n]', elements).letterfx({ $('.i18n-animation[data-i18n]', elements).letterfx({
'fx': 'fall fade', 'fx': 'fall fade',
'backwards': false, 'backwards': false,
@ -174,8 +157,7 @@ export function i18nToNodes(elements, animate = false)
} }
const reloadData = () => { const reloadData = () => {
if (window.rainloopI18N) if (window.rainloopI18N) {
{
I18N_DATA = window.rainloopI18N || {}; I18N_DATA = window.rainloopI18N || {};
i18nToNodes(window.document, true); i18nToNodes(window.document, true);
@ -190,8 +172,7 @@ const reloadData = () => {
/** /**
* @returns {void} * @returns {void}
*/ */
export function initNotificationLanguage() export function initNotificationLanguage() {
{
I18N_NOTIFICATION_MAP.forEach((item) => { I18N_NOTIFICATION_MAP.forEach((item) => {
I18N_NOTIFICATION_DATA[item[0]] = i18n(item[1]); I18N_NOTIFICATION_DATA[item[0]] = i18n(item[1]);
}); });
@ -201,28 +182,21 @@ export function initNotificationLanguage()
* @param {Function} startCallback * @param {Function} startCallback
* @param {Function=} langCallback = null * @param {Function=} langCallback = null
*/ */
export function initOnStartOrLangChange(startCallback, langCallback = null) export function initOnStartOrLangChange(startCallback, langCallback = null) {
{ if (startCallback) {
if (startCallback)
{
startCallback(); startCallback();
} }
if (langCallback) if (langCallback) {
{
trigger.subscribe(() => { trigger.subscribe(() => {
if (startCallback) if (startCallback) {
{
startCallback(); startCallback();
} }
if (langCallback) if (langCallback) {
{
langCallback(); langCallback();
} }
}); });
} } else if (startCallback) {
else if (startCallback)
{
trigger.subscribe(startCallback); trigger.subscribe(startCallback);
} }
} }
@ -233,18 +207,18 @@ export function initOnStartOrLangChange(startCallback, langCallback = null)
* @param {*=} defCode = null * @param {*=} defCode = null
* @returns {string} * @returns {string}
*/ */
export function getNotification(code, message = '', defCode = null) export function getNotification(code, message = '', defCode = null) {
{
code = window.parseInt(code, 10) || 0; code = window.parseInt(code, 10) || 0;
if (Notification.ClientViewError === code && message) if (Notification.ClientViewError === code && message) {
{
return message; return message;
} }
defCode = defCode ? (window.parseInt(defCode, 10)) || 0 : 0; defCode = defCode ? window.parseInt(defCode, 10) || 0 : 0;
return isUnd(I18N_NOTIFICATION_DATA[code]) ? ( return isUnd(I18N_NOTIFICATION_DATA[code])
defCode && isUnd(I18N_NOTIFICATION_DATA[defCode]) ? I18N_NOTIFICATION_DATA[defCode] : '' ? defCode && isUnd(I18N_NOTIFICATION_DATA[defCode])
) : I18N_NOTIFICATION_DATA[code]; ? I18N_NOTIFICATION_DATA[defCode]
: ''
: I18N_NOTIFICATION_DATA[code];
} }
/** /**
@ -252,21 +226,19 @@ export function getNotification(code, message = '', defCode = null)
* @param {number} defCode = Notification.UnknownNotification * @param {number} defCode = Notification.UnknownNotification
* @returns {string} * @returns {string}
*/ */
export function getNotificationFromResponse(response, defCode = Notification.UnknownNotification) export function getNotificationFromResponse(response, defCode = Notification.UnknownNotification) {
{ return response && response.ErrorCode
return response && response.ErrorCode ? ? getNotification(pInt(response.ErrorCode), response.ErrorMessage || '')
getNotification(pInt(response.ErrorCode), response.ErrorMessage || '') : getNotification(defCode); : getNotification(defCode);
} }
/** /**
* @param {*} code * @param {*} code
* @returns {string} * @returns {string}
*/ */
export function getUploadErrorDescByCode(code) export function getUploadErrorDescByCode(code) {
{
let result = ''; let result = '';
switch (window.parseInt(code, 10) || 0) switch (window.parseInt(code, 10) || 0) {
{
case UploadErrorCode.FileIsTooBig: case UploadErrorCode.FileIsTooBig:
result = i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'); result = i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
break; break;
@ -297,8 +269,7 @@ export function getUploadErrorDescByCode(code)
* @param {boolean} admin * @param {boolean} admin
* @param {string} language * @param {string} language
*/ */
export function reload(admin, language) export function reload(admin, language) {
{
const start = microtime(); const start = microtime();
$html.addClass('rl-changing-language'); $html.addClass('rl-changing-language');
@ -308,27 +279,31 @@ export function reload(admin, language)
url: langLink(language, admin), url: langLink(language, admin),
dataType: 'script', dataType: 'script',
cache: true cache: true
}).then(() => { }).then(
_.delay(() => { () => {
_.delay(
() => {
reloadData();
reloadData(); const isRtl = -1 < inArray((language || '').toLowerCase(), ['ar', 'ar_sa', 'he', 'he_he', 'ur', 'ur_ir']);
const isRtl = -1 < inArray((language || '').toLowerCase(), ['ar', 'ar_sa', 'he', 'he_he', 'ur', 'ur_ir']); $html
.removeClass('rl-changing-language')
.removeClass('rl-rtl rl-ltr')
// .attr('dir', isRtl ? 'rtl' : 'ltr')
.addClass(isRtl ? 'rl-rtl' : 'rl-ltr');
$html resolve();
.removeClass('rl-changing-language') },
.removeClass('rl-rtl rl-ltr') 500 < microtime() - start ? 1 : 500
// .attr('dir', isRtl ? 'rtl' : 'ltr') );
.addClass(isRtl ? 'rl-rtl' : 'rl-ltr'); },
() => {
resolve(); $html.removeClass('rl-changing-language');
window.rainloopI18N = null;
}, 500 < microtime() - start ? 1 : 500); reject();
}, () => { }
$html.removeClass('rl-changing-language'); );
window.rainloopI18N = null;
reject();
});
}); });
} }

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,15 @@
import $ from '$'; import $ from '$';
import ko from 'ko'; import ko from 'ko';
import {isUnd} from 'Common/Utils'; import { isUnd } from 'Common/Utils';
import {i18nToNodes} from 'Common/Translator'; import { i18nToNodes } from 'Common/Translator';
class AbstractComponent class AbstractComponent {
{
disposable = []; disposable = [];
dispose() { dispose() {
this.disposable.forEach((funcToDispose) => { this.disposable.forEach((funcToDispose) => {
if (funcToDispose && funcToDispose.dispose) if (funcToDispose && funcToDispose.dispose) {
{
funcToDispose.dispose(); funcToDispose.dispose();
} }
}); });
@ -25,22 +22,19 @@ class AbstractComponent
* @returns {Object} * @returns {Object}
*/ */
const componentExportHelper = (ClassObject, templateID = '') => ({ const componentExportHelper = (ClassObject, templateID = '') => ({
template: templateID ? {element: templateID} : '<b></b>', template: templateID ? { element: templateID } : '<b></b>',
viewModel: { viewModel: {
createViewModel: (params, componentInfo) => { createViewModel: (params, componentInfo) => {
params = params || {}; params = params || {};
params.element = null; params.element = null;
if (componentInfo && componentInfo.element) if (componentInfo && componentInfo.element) {
{
params.component = componentInfo; params.component = componentInfo;
params.element = $(componentInfo.element); params.element = $(componentInfo.element);
i18nToNodes(params.element); i18nToNodes(params.element);
if (!isUnd(params.inline) && ko.unwrap(params.inline)) if (!isUnd(params.inline) && ko.unwrap(params.inline)) {
{
params.element.css('display', 'inline-block'); params.element.css('display', 'inline-block');
} }
} }
@ -50,4 +44,4 @@ const componentExportHelper = (ClassObject, templateID = '') => ({
} }
}); });
export {AbstractComponent, componentExportHelper}; export { AbstractComponent, componentExportHelper };

View file

@ -1,16 +1,13 @@
import ko from 'ko'; import ko from 'ko';
import {isUnd, trim, pInt} from 'Common/Utils'; import { isUnd, trim, pInt } from 'Common/Utils';
import {SaveSettingsStep} from 'Common/Enums'; import { SaveSettingsStep } from 'Common/Enums';
import {AbstractComponent} from 'Component/Abstract'; import { AbstractComponent } from 'Component/Abstract';
class AbstractInput extends AbstractComponent class AbstractInput extends AbstractComponent {
{
/** /**
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
super(); super();
this.value = params.value || ''; this.value = params.value || '';
@ -28,32 +25,26 @@ class AbstractInput extends AbstractComponent
this.classForTrigger = ko.observable(''); this.classForTrigger = ko.observable('');
this.className = ko.computed(() => { this.className = ko.computed(() => {
const const size = ko.unwrap(this.size),
size = ko.unwrap(this.size),
suffixValue = this.trigger ? ' ' + trim('settings-saved-trigger-input ' + this.classForTrigger()) : ''; suffixValue = this.trigger ? ' ' + trim('settings-saved-trigger-input ' + this.classForTrigger()) : '';
return (0 < size ? 'span' + size : '') + suffixValue; return (0 < size ? 'span' + size : '') + suffixValue;
}); });
if (!isUnd(params.width) && params.element) if (!isUnd(params.width) && params.element) {
{
params.element.find('input,select,textarea').css('width', params.width); params.element.find('input,select,textarea').css('width', params.width);
} }
this.disposable.push(this.className); this.disposable.push(this.className);
if (this.trigger) if (this.trigger) {
{
this.setTriggerState(this.trigger()); this.setTriggerState(this.trigger());
this.disposable.push( this.disposable.push(this.trigger.subscribe(this.setTriggerState, this));
this.trigger.subscribe(this.setTriggerState, this)
);
} }
} }
setTriggerState(value) { setTriggerState(value) {
switch (pInt(value)) switch (pInt(value)) {
{
case SaveSettingsStep.TrueResult: case SaveSettingsStep.TrueResult:
this.classForTrigger('success'); this.classForTrigger('success');
break; break;
@ -67,4 +58,4 @@ class AbstractInput extends AbstractComponent
} }
} }
export {AbstractInput, AbstractInput as default}; export { AbstractInput, AbstractInput as default };

View file

@ -1,6 +1,5 @@
import { componentExportHelper } from 'Component/Abstract';
import {componentExportHelper} from 'Component/Abstract'; import { AbstractCheckbox } from 'Component/AbstractCheckbox';
import {AbstractCheckbox} from 'Component/AbstractCheckbox';
class CheckboxComponent extends AbstractCheckbox {} class CheckboxComponent extends AbstractCheckbox {}

View file

@ -1,6 +1,5 @@
import { componentExportHelper } from 'Component/Abstract';
import {componentExportHelper} from 'Component/Abstract'; import { AbstractCheckbox } from 'Component/AbstractCheckbox';
import {AbstractCheckbox} from 'Component/AbstractCheckbox';
class ClassicCheckboxComponent extends AbstractCheckbox {} class ClassicCheckboxComponent extends AbstractCheckbox {}

View file

@ -1,6 +1,5 @@
import { componentExportHelper } from 'Component/Abstract';
import {componentExportHelper} from 'Component/Abstract'; import { AbstractInput } from 'Component/AbstractInput';
import {AbstractInput} from 'Component/AbstractInput';
class DateComponent extends AbstractInput {} class DateComponent extends AbstractInput {}

View file

@ -1,6 +1,5 @@
import { componentExportHelper } from 'Component/Abstract';
import {componentExportHelper} from 'Component/Abstract'; import { AbstractInput } from 'Component/AbstractInput';
import {AbstractInput} from 'Component/AbstractInput';
class InputComponent extends AbstractInput {} class InputComponent extends AbstractInput {}

View file

@ -1,20 +1,17 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {componentExportHelper} from 'Component/Abstract'; import { componentExportHelper } from 'Component/Abstract';
import {AbstractCheckbox} from 'Component/AbstractCheckbox'; import { AbstractCheckbox } from 'Component/AbstractCheckbox';
class CheckboxMaterialDesignComponent extends AbstractCheckbox class CheckboxMaterialDesignComponent extends AbstractCheckbox {
{
/** /**
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
super(params); super(params);
this.animationBox = ko.observable(false).extend({falseTimeout: 200}); this.animationBox = ko.observable(false).extend({ falseTimeout: 200 });
this.animationCheckmark = ko.observable(false).extend({falseTimeout: 200}); this.animationCheckmark = ko.observable(false).extend({ falseTimeout: 200 });
this.animationBoxSetTrue = _.bind(this.animationBoxSetTrue, this); this.animationBoxSetTrue = _.bind(this.animationBoxSetTrue, this);
this.animationCheckmarkSetTrue = _.bind(this.animationCheckmarkSetTrue, this); this.animationCheckmarkSetTrue = _.bind(this.animationCheckmarkSetTrue, this);
@ -38,8 +35,7 @@ class CheckboxMaterialDesignComponent extends AbstractCheckbox
if (box) { if (box) {
this.animationBoxSetTrue(); this.animationBoxSetTrue();
_.delay(this.animationCheckmarkSetTrue, 200); _.delay(this.animationCheckmarkSetTrue, 200);
} } else {
else {
this.animationCheckmarkSetTrue(); this.animationCheckmarkSetTrue();
_.delay(this.animationBoxSetTrue, 200); _.delay(this.animationBoxSetTrue, 200);
} }

View file

@ -1,6 +1,5 @@
import { componentExportHelper } from 'Component/Abstract';
import {componentExportHelper} from 'Component/Abstract'; import { AbstractRadio } from 'Component/AbstractRadio';
import {AbstractRadio} from 'Component/AbstractRadio';
class RadioComponent extends AbstractRadio {} class RadioComponent extends AbstractRadio {}

View file

@ -1,72 +1,74 @@
import { pInt } from 'Common/Utils';
import { SaveSettingsStep } from 'Common/Enums';
import { AbstractComponent, componentExportHelper } from 'Component/Abstract';
import {pInt} from 'Common/Utils'; class SaveTriggerComponent extends AbstractComponent {
import {SaveSettingsStep} from 'Common/Enums';
import {AbstractComponent, componentExportHelper} from 'Component/Abstract';
class SaveTriggerComponent extends AbstractComponent
{
/** /**
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
super(); super();
this.element = params.element || null; this.element = params.element || null;
this.value = params.value && params.value.subscribe ? params.value : null; this.value = params.value && params.value.subscribe ? params.value : null;
if (this.element) if (this.element) {
{ if (this.value) {
if (this.value)
{
this.element.css('display', 'inline-block'); this.element.css('display', 'inline-block');
if (params.verticalAlign) if (params.verticalAlign) {
{
this.element.css('vertical-align', params.verticalAlign); this.element.css('vertical-align', params.verticalAlign);
} }
this.setState(this.value()); this.setState(this.value());
this.disposable.push( this.disposable.push(this.value.subscribe(this.setState, this));
this.value.subscribe(this.setState, this) } else {
);
}
else
{
this.element.hide(); this.element.hide();
} }
} }
} }
setState(value) { setState(value) {
switch (pInt(value)) {
switch (pInt(value))
{
case SaveSettingsStep.TrueResult: case SaveSettingsStep.TrueResult:
this.element this.element
.find('.animated,.error').hide().removeClass('visible') .find('.animated,.error')
.hide()
.removeClass('visible')
.end() .end()
.find('.success').show().addClass('visible'); .find('.success')
.show()
.addClass('visible');
break; break;
case SaveSettingsStep.FalseResult: case SaveSettingsStep.FalseResult:
this.element this.element
.find('.animated,.success').hide().removeClass('visible') .find('.animated,.success')
.hide()
.removeClass('visible')
.end() .end()
.find('.error').show().addClass('visible'); .find('.error')
.show()
.addClass('visible');
break; break;
case SaveSettingsStep.Animate: case SaveSettingsStep.Animate:
this.element this.element
.find('.error,.success').hide().removeClass('visible') .find('.error,.success')
.hide()
.removeClass('visible')
.end() .end()
.find('.animated').show().addClass('visible'); .find('.animated')
.show()
.addClass('visible');
break; break;
case SaveSettingsStep.Idle: case SaveSettingsStep.Idle:
default: default:
this.element this.element
.find('.animated').hide() .find('.animated')
.hide()
.end() .end()
.find('.error,.success').removeClass('visible'); .find('.error,.success')
.removeClass('visible');
break; break;
} }
} }

View file

@ -1,36 +1,33 @@
import $ from '$'; import $ from '$';
import {AbstractComponent, componentExportHelper} from 'Component/Abstract'; import { AbstractComponent, componentExportHelper } from 'Component/Abstract';
class ScriptComponent extends AbstractComponent class ScriptComponent extends AbstractComponent {
{
/** /**
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
super(); super();
if (params.component && params.component.templateNodes && params.element && if (
params.element[0] && params.element[0].outerHTML) params.component &&
{ params.component.templateNodes &&
params.element &&
params.element[0] &&
params.element[0].outerHTML
) {
let script = params.element[0].outerHTML; let script = params.element[0].outerHTML;
script = !script ? '' : script script = !script ? '' : script.replace(/<x-script/i, '<script').replace(/<b><\/b><\/x-script>/i, '</script>');
.replace(/<x-script/i, '<script')
.replace(/<b><\/b><\/x-script>/i, '</script>');
if (script) if (script) {
{
params.element.text(''); params.element.text('');
params.element.replaceWith( params.element.replaceWith(
$(script).text( $(script).text(
params.component.templateNodes[0] && params.component.templateNodes[0].nodeValue ? params.component.templateNodes[0] && params.component.templateNodes[0].nodeValue
params.component.templateNodes[0].nodeValue : '' ? params.component.templateNodes[0].nodeValue
: ''
) )
); );
} } else {
else
{
params.element.remove(); params.element.remove();
} }
} }

View file

@ -1,16 +1,13 @@
import { i18n } from 'Common/Translator';
import { defautOptionsAfterRender } from 'Common/Utils';
import { componentExportHelper } from 'Component/Abstract';
import { AbstractInput } from 'Component/AbstractInput';
import {i18n} from 'Common/Translator'; class SelectComponent extends AbstractInput {
import {defautOptionsAfterRender} from 'Common/Utils';
import {componentExportHelper} from 'Component/Abstract';
import {AbstractInput} from 'Component/AbstractInput';
class SelectComponent extends AbstractInput
{
/** /**
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
super(params); super(params);
this.options = params.options || ''; this.options = params.options || '';
@ -19,8 +16,7 @@ class SelectComponent extends AbstractInput
this.optionsValue = params.optionsValue || null; this.optionsValue = params.optionsValue || null;
this.optionsCaption = params.optionsCaption || null; this.optionsCaption = params.optionsCaption || null;
if (this.optionsCaption) if (this.optionsCaption) {
{
this.optionsCaption = i18n(this.optionsCaption); this.optionsCaption = i18n(this.optionsCaption);
} }

View file

@ -1,10 +1,8 @@
import $ from '$'; import $ from '$';
let cachedUrl = null; let cachedUrl = null;
const getUrl = () => { const getUrl = () => {
if (!cachedUrl) if (!cachedUrl) {
{
const version = $('#rlAppVersion').attr('content') || '0.0.0'; const version = $('#rlAppVersion').attr('content') || '0.0.0';
cachedUrl = `rainloop/v/${version}/static/css/svg/icons.svg`; cachedUrl = `rainloop/v/${version}/static/css/svg/icons.svg`;
} }
@ -15,9 +13,8 @@ const getUrl = () => {
export default { export default {
template: '<b></b>', template: '<b></b>',
viewModel: { viewModel: {
createViewModel: ({icon = 'null'}, componentInfo) => { createViewModel: ({ icon = 'null' }, componentInfo) => {
if (componentInfo && componentInfo.element) if (componentInfo && componentInfo.element) {
{
$(componentInfo.element).replaceWith( $(componentInfo.element).replaceWith(
`<svg class="svg-icon svg-icon-${icon}"><use xlink:href="${getUrl()}#svg-icon-${icon}"></use></svg>` `<svg class="svg-icon svg-icon-${icon}"><use xlink:href="${getUrl()}#svg-icon-${icon}"></use></svg>`
); );

View file

@ -1,17 +1,14 @@
import { isUnd } from 'Common/Utils';
import {isUnd} from 'Common/Utils'; import { componentExportHelper } from 'Component/Abstract';
import {componentExportHelper} from 'Component/Abstract'; import { AbstractInput } from 'Component/AbstractInput';
import {AbstractInput} from 'Component/AbstractInput';
const DEFAULT_ROWS = 5; const DEFAULT_ROWS = 5;
class TextAreaComponent extends AbstractInput class TextAreaComponent extends AbstractInput {
{
/** /**
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
super(params); super(params);
this.rows = params.rows || DEFAULT_ROWS; this.rows = params.rows || DEFAULT_ROWS;

View file

@ -1,4 +1,3 @@
import window from 'window'; import window from 'window';
const Opentip = window.Opentip || {}; const Opentip = window.Opentip || {};
@ -6,7 +5,6 @@ const Opentip = window.Opentip || {};
Opentip.styles = Opentip.styles || {}; Opentip.styles = Opentip.styles || {};
Opentip.styles.rainloop = { Opentip.styles.rainloop = {
'extends': 'standard', 'extends': 'standard',
'fixed': true, 'fixed': true,
@ -43,4 +41,4 @@ Opentip.styles.rainloopErrorTip = {
'className': 'rainloopErrorTip' 'className': 'rainloopErrorTip'
}; };
export {Opentip, Opentip as default}; export { Opentip, Opentip as default };

535
dev/External/ko.js vendored

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,3 @@
/** /**
* @returns {AppAdmin} * @returns {AppAdmin}
*/ */

View file

@ -1,4 +1,3 @@
/** /**
* @returns {AppUser} * @returns {AppUser}
*/ */

View file

@ -1,6 +1,5 @@
import { isNonEmptyArray, isUnd } from 'Common/Utils';
import {isNonEmptyArray, isUnd} from 'Common/Utils'; import { EmailModel } from 'Model/Email';
import {EmailModel} from 'Model/Email';
/** /**
* @param {Array.<EmailModel>} emails * @param {Array.<EmailModel>} emails
@ -9,15 +8,12 @@ import {EmailModel} from 'Model/Email';
* @returns {string} * @returns {string}
*/ */
export function emailArrayToString(emails, friendlyView = false, wrapWithLink = false) { export function emailArrayToString(emails, friendlyView = false, wrapWithLink = false) {
let let index = 0,
index = 0,
len = 0; len = 0;
const result = []; const result = [];
if (isNonEmptyArray(emails)) if (isNonEmptyArray(emails)) {
{ for (len = emails.length; index < len; index++) {
for (len = emails.length; index < len; index++)
{
result.push(emails[index].toLine(friendlyView, wrapWithLink)); result.push(emails[index].toLine(friendlyView, wrapWithLink));
} }
} }
@ -30,17 +26,13 @@ export function emailArrayToString(emails, friendlyView = false, wrapWithLink =
* @returns {string} * @returns {string}
*/ */
export function emailArrayToStringClear(emails) { export function emailArrayToStringClear(emails) {
let let index = 0,
index = 0,
len = 0; len = 0;
const result = []; const result = [];
if (isNonEmptyArray(emails)) if (isNonEmptyArray(emails)) {
{ for (len = emails.length; index < len; index++) {
for (len = emails.length; index < len; index++) if (emails[index] && emails[index].email && '' !== emails[index].name) {
{
if (emails[index] && emails[index].email && '' !== emails[index].name)
{
result.push(emails[index].email); result.push(emails[index].email);
} }
} }
@ -54,19 +46,15 @@ export function emailArrayToStringClear(emails) {
* @returns {Array.<EmailModel>} * @returns {Array.<EmailModel>}
*/ */
export function emailArrayFromJson(json) { export function emailArrayFromJson(json) {
let let index = 0,
index = 0,
len = 0, len = 0,
email = null; email = null;
const result = []; const result = [];
if (isNonEmptyArray(json)) if (isNonEmptyArray(json)) {
{ for (index = 0, len = json.length; index < len; index++) {
for (index = 0, len = json.length; index < len; index++)
{
email = EmailModel.newInstanceFromJson(json[index]); email = EmailModel.newInstanceFromJson(json[index]);
if (email) if (email) {
{
result.push(email); result.push(email);
} }
} }
@ -81,16 +69,12 @@ export function emailArrayFromJson(json) {
* @param {Array} localEmails * @param {Array} localEmails
*/ */
export function replyHelper(inputEmails, unic, localEmails) { export function replyHelper(inputEmails, unic, localEmails) {
if (inputEmails && 0 < inputEmails.length) {
if (inputEmails && 0 < inputEmails.length)
{
let index = 0; let index = 0;
const len = inputEmails.length; const len = inputEmails.length;
for (; index < len; index++) for (; index < len; index++) {
{ if (isUnd(unic[inputEmails[index].email])) {
if (isUnd(unic[inputEmails[index].email]))
{
unic[inputEmails[index].email] = true; unic[inputEmails[index].email] = true;
localEmails.push(inputEmails[index]); localEmails.push(inputEmails[index]);
} }

View file

@ -1,5 +1,5 @@
export class AbstractBoot {
export class AbstractBoot bootstart() {
{ /* no-empty */
bootstart() {/* no-empty */} }
} }

View file

@ -1,33 +1,27 @@
import { isArray, disposeObject } from 'Common/Utils';
import {isArray, disposeObject} from 'Common/Utils'; export class AbstractModel {
export class AbstractModel
{
sModelName = ''; sModelName = '';
disposables = []; disposables = [];
/** /**
* @param {string} modelName = '' * @param {string} modelName = ''
*/ */
constructor(modelName = '') constructor(modelName = '') {
{
this.sModelName = modelName || ''; this.sModelName = modelName || '';
} }
regDisposables(value) { regDisposables(value) {
if (isArray(value)) if (isArray(value)) {
{
value.forEach((item) => { value.forEach((item) => {
this.disposables.push(item); this.disposables.push(item);
}); });
} } else if (value) {
else if (value)
{
this.disposables.push(value); this.disposables.push(value);
} }
} }
onDestroy() { onDestroy() {
disposeObject(this); disposeObject(this);
} }
} }

View file

@ -1,16 +1,13 @@
import _ from '_'; import _ from '_';
import crossroads from 'crossroads'; import crossroads from 'crossroads';
import {isArray, isNonEmptyArray, noop} from 'Common/Utils'; import { isArray, isNonEmptyArray, noop } from 'Common/Utils';
export class AbstractScreen export class AbstractScreen {
{
oCross = null; oCross = null;
sScreenName; sScreenName;
aViewModels; aViewModels;
constructor(screenName, viewModels = []) constructor(screenName, viewModels = []) {
{
this.sScreenName = screenName; this.sScreenName = screenName;
this.aViewModels = isArray(viewModels) ? viewModels : []; this.aViewModels = isArray(viewModels) ? viewModels : [];
} }
@ -47,19 +44,16 @@ export class AbstractScreen
* @returns {void} * @returns {void}
*/ */
__start() { __start() {
let let route = null,
route = null,
fMatcher = null; fMatcher = null;
const routes = this.routes(); const routes = this.routes();
if (isNonEmptyArray(routes)) if (isNonEmptyArray(routes)) {
{
fMatcher = _.bind(this.onRoute || noop, this); fMatcher = _.bind(this.onRoute || noop, this);
route = crossroads.create(); route = crossroads.create();
routes.forEach((item) => { routes.forEach((item) => {
if (item && route) if (item && route) {
{
route.addRoute(item[0], fMatcher).rules = item[1]; route.addRoute(item[0], fMatcher).rules = item[1];
} }
}); });

View file

@ -1,18 +1,16 @@
import ko from 'ko'; import ko from 'ko';
import {delegateRun, inFocus} from 'Common/Utils'; import { delegateRun, inFocus } from 'Common/Utils';
import {KeyState, EventKeyCode} from 'Common/Enums'; import { KeyState, EventKeyCode } from 'Common/Enums';
import {$win, keyScope} from 'Common/Globals'; import { $win, keyScope } from 'Common/Globals';
export class AbstractViewNext export class AbstractViewNext {
{
bDisabeCloseOnEsc = false; bDisabeCloseOnEsc = false;
sDefaultKeyScope = KeyState.None; sDefaultKeyScope = KeyState.None;
sCurrentKeyScope = KeyState.None; sCurrentKeyScope = KeyState.None;
viewModelVisibility = ko.observable(false); viewModelVisibility = ko.observable(false);
modalVisibility = ko.observable(false).extend({rateLimit: 0}); modalVisibility = ko.observable(false).extend({ rateLimit: 0 });
viewModelName = ''; viewModelName = '';
viewModelNames = []; viewModelNames = [];
@ -38,15 +36,11 @@ export class AbstractViewNext
*/ */
registerPopupKeyDown() { registerPopupKeyDown() {
$win.on('keydown', (event) => { $win.on('keydown', (event) => {
if (event && this.modalVisibility && this.modalVisibility()) if (event && this.modalVisibility && this.modalVisibility()) {
{ if (!this.bDisabeCloseOnEsc && EventKeyCode.Esc === event.keyCode) {
if (!this.bDisabeCloseOnEsc && EventKeyCode.Esc === event.keyCode)
{
delegateRun(this, 'cancelCommand'); delegateRun(this, 'cancelCommand');
return false; return false;
} } else if (EventKeyCode.Backspace === event.keyCode && !inFocus()) {
else if (EventKeyCode.Backspace === event.keyCode && !inFocus())
{
return false; return false;
} }
} }

View file

@ -1,21 +1,16 @@
import _ from '_'; import _ from '_';
import $ from '$'; import $ from '$';
import ko from 'ko'; import ko from 'ko';
import hasher from 'hasher'; import hasher from 'hasher';
import crossroads from 'crossroads'; import crossroads from 'crossroads';
import {Magics} from 'Common/Enums'; import { Magics } from 'Common/Enums';
import {runHook} from 'Common/Plugins'; import { runHook } from 'Common/Plugins';
import {$html, VIEW_MODELS, popupVisibilityNames} from 'Common/Globals'; import { $html, VIEW_MODELS, popupVisibilityNames } from 'Common/Globals';
import { import { isArray, isUnd, pString, log, isFunc, createCommandLegacy, delegateRun, isNonEmptyArray } from 'Common/Utils';
isArray, isUnd, pString, log, isFunc,
createCommandLegacy, delegateRun, isNonEmptyArray
} from 'Common/Utils';
let let currentScreen = null,
currentScreen = null,
defaultScreenName = ''; defaultScreenName = '';
const SCREENS = {}; const SCREENS = {};
@ -30,10 +25,11 @@ export const ViewType = {
/** /**
* @returns {void} * @returns {void}
*/ */
export function hideLoading() export function hideLoading() {
{
$('#rl-content').addClass('rl-content-show'); $('#rl-content').addClass('rl-content-show');
$('#rl-loading').hide().remove(); $('#rl-loading')
.hide()
.remove();
} }
/** /**
@ -41,8 +37,7 @@ export function hideLoading()
* @param {(Function|boolean|null)=} fCanExecute = true * @param {(Function|boolean|null)=} fCanExecute = true
* @returns {Function} * @returns {Function}
*/ */
export function createCommand(fExecute, fCanExecute = true) export function createCommand(fExecute, fCanExecute = true) {
{
return createCommandLegacy(null, fExecute, fCanExecute); return createCommandLegacy(null, fExecute, fCanExecute);
} }
@ -54,8 +49,7 @@ export function createCommand(fExecute, fCanExecute = true)
* @param {boolean=} isDefault = false * @param {boolean=} isDefault = false
* @returns {void} * @returns {void}
*/ */
export function addSettingsViewModel(SettingsViewModelClass, template, labelName, route, isDefault = false) export function addSettingsViewModel(SettingsViewModelClass, template, labelName, route, isDefault = false) {
{
SettingsViewModelClass.__rlSettingsData = { SettingsViewModelClass.__rlSettingsData = {
Label: labelName, Label: labelName,
Template: template, Template: template,
@ -70,8 +64,7 @@ export function addSettingsViewModel(SettingsViewModelClass, template, labelName
* @param {Function} SettingsViewModelClass * @param {Function} SettingsViewModelClass
* @returns {void} * @returns {void}
*/ */
export function removeSettingsViewModel(SettingsViewModelClass) export function removeSettingsViewModel(SettingsViewModelClass) {
{
VIEW_MODELS['settings-removed'].push(SettingsViewModelClass); VIEW_MODELS['settings-removed'].push(SettingsViewModelClass);
} }
@ -79,24 +72,21 @@ export function removeSettingsViewModel(SettingsViewModelClass)
* @param {Function} SettingsViewModelClass * @param {Function} SettingsViewModelClass
* @returns {void} * @returns {void}
*/ */
export function disableSettingsViewModel(SettingsViewModelClass) export function disableSettingsViewModel(SettingsViewModelClass) {
{
VIEW_MODELS['settings-disabled'].push(SettingsViewModelClass); VIEW_MODELS['settings-disabled'].push(SettingsViewModelClass);
} }
/** /**
* @returns {void} * @returns {void}
*/ */
export function routeOff() export function routeOff() {
{
hasher.changed.active = false; hasher.changed.active = false;
} }
/** /**
* @returns {void} * @returns {void}
*/ */
export function routeOn() export function routeOn() {
{
hasher.changed.active = true; hasher.changed.active = true;
} }
@ -104,23 +94,19 @@ export function routeOn()
* @param {string} screenName * @param {string} screenName
* @returns {?Object} * @returns {?Object}
*/ */
export function screen(screenName) export function screen(screenName) {
{ return '' !== screenName && !isUnd(SCREENS[screenName]) ? SCREENS[screenName] : null;
return ('' !== screenName && !isUnd(SCREENS[screenName])) ? SCREENS[screenName] : null;
} }
/** /**
* @param {Function} ViewModelClassToShow * @param {Function} ViewModelClassToShow
* @returns {Function|null} * @returns {Function|null}
*/ */
export function getScreenPopup(PopuViewModelClass) export function getScreenPopup(PopuViewModelClass) {
{
let result = null; let result = null;
if (PopuViewModelClass) if (PopuViewModelClass) {
{
result = PopuViewModelClass; result = PopuViewModelClass;
if (PopuViewModelClass.default) if (PopuViewModelClass.default) {
{
result = PopuViewModelClass.default; result = PopuViewModelClass.default;
} }
} }
@ -132,11 +118,9 @@ export function getScreenPopup(PopuViewModelClass)
* @param {Function} ViewModelClassToHide * @param {Function} ViewModelClassToHide
* @returns {void} * @returns {void}
*/ */
export function hideScreenPopup(ViewModelClassToHide) export function hideScreenPopup(ViewModelClassToHide) {
{
const ModalView = getScreenPopup(ViewModelClassToHide); const ModalView = getScreenPopup(ViewModelClassToHide);
if (ModalView && ModalView.__vm && ModalView.__dom) if (ModalView && ModalView.__vm && ModalView.__dom) {
{
ModalView.__vm.modalVisibility(false); ModalView.__vm.modalVisibility(false);
} }
} }
@ -146,8 +130,7 @@ export function hideScreenPopup(ViewModelClassToHide)
* @param {Function} ViewModelClass * @param {Function} ViewModelClass
* @param {mixed=} params = null * @param {mixed=} params = null
*/ */
export function vmRunHook(hookName, ViewModelClass, params = null) export function vmRunHook(hookName, ViewModelClass, params = null) {
{
_.each(ViewModelClass.__names, (name) => { _.each(ViewModelClass.__names, (name) => {
runHook(hookName, [name, ViewModelClass.__vm, params]); runHook(hookName, [name, ViewModelClass.__vm, params]);
}); });
@ -158,13 +141,10 @@ export function vmRunHook(hookName, ViewModelClass, params = null)
* @param {Object=} vmScreen * @param {Object=} vmScreen
* @returns {*} * @returns {*}
*/ */
export function buildViewModel(ViewModelClass, vmScreen) export function buildViewModel(ViewModelClass, vmScreen) {
{ if (ViewModelClass && !ViewModelClass.__builded) {
if (ViewModelClass && !ViewModelClass.__builded)
{
let vmDom = null; let vmDom = null;
const const vm = new ViewModelClass(vmScreen),
vm = new ViewModelClass(vmScreen),
position = ViewModelClass.__type || '', position = ViewModelClass.__type || '',
vmPlace = position ? $('#rl-content #rl-' + position.toLowerCase()) : null; vmPlace = position ? $('#rl-content #rl-' + position.toLowerCase()) : null;
@ -179,43 +159,39 @@ export function buildViewModel(ViewModelClass, vmScreen)
vm.viewModelTemplateID = ViewModelClass.__templateID; vm.viewModelTemplateID = ViewModelClass.__templateID;
vm.viewModelPosition = ViewModelClass.__type; vm.viewModelPosition = ViewModelClass.__type;
if (vmPlace && 1 === vmPlace.length) if (vmPlace && 1 === vmPlace.length) {
{ vmDom = $('<div></div>')
vmDom = $('<div></div>').addClass('rl-view-model').addClass('RL-' + vm.viewModelTemplateID).hide(); .addClass('rl-view-model')
.addClass('RL-' + vm.viewModelTemplateID)
.hide();
vmDom.appendTo(vmPlace); vmDom.appendTo(vmPlace);
vm.viewModelDom = vmDom; vm.viewModelDom = vmDom;
ViewModelClass.__dom = vmDom; ViewModelClass.__dom = vmDom;
if (ViewType.Popup === position) if (ViewType.Popup === position) {
{
vm.cancelCommand = vm.closeCommand = createCommand(() => { vm.cancelCommand = vm.closeCommand = createCommand(() => {
hideScreenPopup(ViewModelClass); hideScreenPopup(ViewModelClass);
}); });
vm.modalVisibility.subscribe((value) => { vm.modalVisibility.subscribe((value) => {
if (value) if (value) {
{
vm.viewModelDom.show(); vm.viewModelDom.show();
vm.storeAndSetKeyScope(); vm.storeAndSetKeyScope();
popupVisibilityNames.push(vm.viewModelName); popupVisibilityNames.push(vm.viewModelName);
vm.viewModelDom.css('z-index', 3000 + popupVisibilityNames().length + 10); vm.viewModelDom.css('z-index', 3000 + popupVisibilityNames().length + 10);
if (vm.onShowTrigger) if (vm.onShowTrigger) {
{
vm.onShowTrigger(!vm.onShowTrigger()); vm.onShowTrigger(!vm.onShowTrigger());
} }
delegateRun(vm, 'onShowWithDelay', [], 500); delegateRun(vm, 'onShowWithDelay', [], 500);
} } else {
else
{
delegateRun(vm, 'onHide'); delegateRun(vm, 'onHide');
delegateRun(vm, 'onHideWithDelay', [], 500); delegateRun(vm, 'onHideWithDelay', [], 500);
if (vm.onHideTrigger) if (vm.onHideTrigger) {
{
vm.onHideTrigger(!vm.onHideTrigger()); vm.onHideTrigger(!vm.onHideTrigger());
} }
@ -233,21 +209,22 @@ export function buildViewModel(ViewModelClass, vmScreen)
vmRunHook('view-model-pre-build', ViewModelClass, vmDom); vmRunHook('view-model-pre-build', ViewModelClass, vmDom);
ko.applyBindingAccessorsToNode(vmDom[0], { ko.applyBindingAccessorsToNode(
translatorInit: true, vmDom[0],
template: () => ({name: vm.viewModelTemplateID}) {
}, vm); translatorInit: true,
template: () => ({ name: vm.viewModelTemplateID })
},
vm
);
delegateRun(vm, 'onBuild', [vmDom]); delegateRun(vm, 'onBuild', [vmDom]);
if (vm && ViewType.Popup === position) if (vm && ViewType.Popup === position) {
{
vm.registerPopupKeyDown(); vm.registerPopupKeyDown();
} }
vmRunHook('view-model-post-build', ViewModelClass, vmDom); vmRunHook('view-model-post-build', ViewModelClass, vmDom);
} } else {
else
{
log('Cannot find view model position: ' + position); log('Cannot find view model position: ' + position);
} }
} }
@ -260,15 +237,12 @@ export function buildViewModel(ViewModelClass, vmScreen)
* @param {Array=} params * @param {Array=} params
* @returns {void} * @returns {void}
*/ */
export function showScreenPopup(ViewModelClassToShow, params = []) export function showScreenPopup(ViewModelClassToShow, params = []) {
{
const ModalView = getScreenPopup(ViewModelClassToShow); const ModalView = getScreenPopup(ViewModelClassToShow);
if (ModalView) if (ModalView) {
{
buildViewModel(ModalView); buildViewModel(ModalView);
if (ModalView.__vm && ModalView.__dom) if (ModalView.__vm && ModalView.__dom) {
{
delegateRun(ModalView.__vm, 'onBeforeShow', params || []); delegateRun(ModalView.__vm, 'onBeforeShow', params || []);
ModalView.__vm.modalVisibility(true); ModalView.__vm.modalVisibility(true);
@ -284,15 +258,12 @@ export function showScreenPopup(ViewModelClassToShow, params = [])
* @param {Function} ViewModelClassToShow * @param {Function} ViewModelClassToShow
* @returns {void} * @returns {void}
*/ */
export function warmUpScreenPopup(ViewModelClassToShow) export function warmUpScreenPopup(ViewModelClassToShow) {
{
const ModalView = getScreenPopup(ViewModelClassToShow); const ModalView = getScreenPopup(ViewModelClassToShow);
if (ModalView) if (ModalView) {
{
buildViewModel(ModalView); buildViewModel(ModalView);
if (ModalView.__vm && ModalView.__dom) if (ModalView.__vm && ModalView.__dom) {
{
delegateRun(ModalView.__vm, 'onWarmUp'); delegateRun(ModalView.__vm, 'onWarmUp');
} }
} }
@ -302,8 +273,7 @@ export function warmUpScreenPopup(ViewModelClassToShow)
* @param {Function} ViewModelClassToShow * @param {Function} ViewModelClassToShow
* @returns {boolean} * @returns {boolean}
*/ */
export function isPopupVisible(ViewModelClassToShow) export function isPopupVisible(ViewModelClassToShow) {
{
const ModalView = getScreenPopup(ViewModelClassToShow); const ModalView = getScreenPopup(ViewModelClassToShow);
return ModalView && ModalView.__vm ? ModalView.__vm.modalVisibility() : false; return ModalView && ModalView.__vm ? ModalView.__vm.modalVisibility() : false;
} }
@ -313,41 +283,32 @@ export function isPopupVisible(ViewModelClassToShow)
* @param {string} subPart * @param {string} subPart
* @returns {void} * @returns {void}
*/ */
export function screenOnRoute(screenName, subPart) export function screenOnRoute(screenName, subPart) {
{ let vmScreen = null,
let
vmScreen = null,
isSameScreen = false, isSameScreen = false,
cross = null; cross = null;
if ('' === pString(screenName)) if ('' === pString(screenName)) {
{
screenName = defaultScreenName; screenName = defaultScreenName;
} }
if ('' !== screenName) if ('' !== screenName) {
{
vmScreen = screen(screenName); vmScreen = screen(screenName);
if (!vmScreen) if (!vmScreen) {
{
vmScreen = screen(defaultScreenName); vmScreen = screen(defaultScreenName);
if (vmScreen) if (vmScreen) {
{
subPart = screenName + '/' + subPart; subPart = screenName + '/' + subPart;
screenName = defaultScreenName; screenName = defaultScreenName;
} }
} }
if (vmScreen && vmScreen.__started) if (vmScreen && vmScreen.__started) {
{
isSameScreen = currentScreen && vmScreen === currentScreen; isSameScreen = currentScreen && vmScreen === currentScreen;
if (!vmScreen.__builded) if (!vmScreen.__builded) {
{
vmScreen.__builded = true; vmScreen.__builded = true;
if (isNonEmptyArray(vmScreen.viewModels())) if (isNonEmptyArray(vmScreen.viewModels())) {
{
_.each(vmScreen.viewModels(), (ViewModelClass) => { _.each(vmScreen.viewModels(), (ViewModelClass) => {
buildViewModel(ViewModelClass, vmScreen); buildViewModel(ViewModelClass, vmScreen);
}); });
@ -358,29 +319,28 @@ export function screenOnRoute(screenName, subPart)
_.defer(() => { _.defer(() => {
// hide screen // hide screen
if (currentScreen && !isSameScreen) if (currentScreen && !isSameScreen) {
{
delegateRun(currentScreen, 'onHide'); delegateRun(currentScreen, 'onHide');
delegateRun(currentScreen, 'onHideWithDelay', [], 500); delegateRun(currentScreen, 'onHideWithDelay', [], 500);
if (currentScreen.onHideTrigger) if (currentScreen.onHideTrigger) {
{
currentScreen.onHideTrigger(!currentScreen.onHideTrigger()); currentScreen.onHideTrigger(!currentScreen.onHideTrigger());
} }
if (isNonEmptyArray(currentScreen.viewModels())) if (isNonEmptyArray(currentScreen.viewModels())) {
{
_.each(currentScreen.viewModels(), (ViewModelClass) => { _.each(currentScreen.viewModels(), (ViewModelClass) => {
if (ViewModelClass.__vm && ViewModelClass.__dom && ViewType.Popup !== ViewModelClass.__vm.viewModelPosition) if (
{ ViewModelClass.__vm &&
ViewModelClass.__dom &&
ViewType.Popup !== ViewModelClass.__vm.viewModelPosition
) {
ViewModelClass.__dom.hide(); ViewModelClass.__dom.hide();
ViewModelClass.__vm.viewModelVisibility(false); ViewModelClass.__vm.viewModelVisibility(false);
delegateRun(ViewModelClass.__vm, 'onHide'); delegateRun(ViewModelClass.__vm, 'onHide');
delegateRun(ViewModelClass.__vm, 'onHideWithDelay', [], 500); delegateRun(ViewModelClass.__vm, 'onHideWithDelay', [], 500);
if (ViewModelClass.__vm.onHideTrigger) if (ViewModelClass.__vm.onHideTrigger) {
{
ViewModelClass.__vm.onHideTrigger(!ViewModelClass.__vm.onHideTrigger()); ViewModelClass.__vm.onHideTrigger(!ViewModelClass.__vm.onHideTrigger());
} }
} }
@ -392,45 +352,41 @@ export function screenOnRoute(screenName, subPart)
currentScreen = vmScreen; currentScreen = vmScreen;
// show screen // show screen
if (currentScreen && !isSameScreen) if (currentScreen && !isSameScreen) {
{
delegateRun(currentScreen, 'onShow'); delegateRun(currentScreen, 'onShow');
if (currentScreen.onShowTrigger) if (currentScreen.onShowTrigger) {
{
currentScreen.onShowTrigger(!currentScreen.onShowTrigger()); currentScreen.onShowTrigger(!currentScreen.onShowTrigger());
} }
runHook('screen-on-show', [currentScreen.screenName(), currentScreen]); runHook('screen-on-show', [currentScreen.screenName(), currentScreen]);
if (isNonEmptyArray(currentScreen.viewModels())) if (isNonEmptyArray(currentScreen.viewModels())) {
{
_.each(currentScreen.viewModels(), (ViewModelClass) => { _.each(currentScreen.viewModels(), (ViewModelClass) => {
if (
if (ViewModelClass.__vm && ViewModelClass.__dom && ViewType.Popup !== ViewModelClass.__vm.viewModelPosition) ViewModelClass.__vm &&
{ ViewModelClass.__dom &&
ViewType.Popup !== ViewModelClass.__vm.viewModelPosition
) {
delegateRun(ViewModelClass.__vm, 'onBeforeShow'); delegateRun(ViewModelClass.__vm, 'onBeforeShow');
ViewModelClass.__dom.show(); ViewModelClass.__dom.show();
ViewModelClass.__vm.viewModelVisibility(true); ViewModelClass.__vm.viewModelVisibility(true);
delegateRun(ViewModelClass.__vm, 'onShow'); delegateRun(ViewModelClass.__vm, 'onShow');
if (ViewModelClass.__vm.onShowTrigger) if (ViewModelClass.__vm.onShowTrigger) {
{
ViewModelClass.__vm.onShowTrigger(!ViewModelClass.__vm.onShowTrigger()); ViewModelClass.__vm.onShowTrigger(!ViewModelClass.__vm.onShowTrigger());
} }
delegateRun(ViewModelClass.__vm, 'onShowWithDelay', [], 200); delegateRun(ViewModelClass.__vm, 'onShowWithDelay', [], 200);
vmRunHook('view-model-on-show', ViewModelClass); vmRunHook('view-model-on-show', ViewModelClass);
} }
}); });
} }
} }
// -- // --
cross = vmScreen && vmScreen.__cross ? vmScreen.__cross() : null; cross = vmScreen && vmScreen.__cross ? vmScreen.__cross() : null;
if (cross) if (cross) {
{
cross.parse(subPart); cross.parse(subPart);
} }
}); });
@ -442,19 +398,14 @@ export function screenOnRoute(screenName, subPart)
* @param {Array} screensClasses * @param {Array} screensClasses
* @returns {void} * @returns {void}
*/ */
export function startScreens(screensClasses) export function startScreens(screensClasses) {
{
_.each(screensClasses, (CScreen) => { _.each(screensClasses, (CScreen) => {
if (CScreen) if (CScreen) {
{ const vmScreen = new CScreen(),
const
vmScreen = new CScreen(),
screenName = vmScreen ? vmScreen.screenName() : ''; screenName = vmScreen ? vmScreen.screenName() : '';
if (vmScreen && '' !== screenName) if (vmScreen && '' !== screenName) {
{ if ('' === defaultScreenName) {
if ('' === defaultScreenName)
{
defaultScreenName = screenName; defaultScreenName = screenName;
} }
@ -464,8 +415,7 @@ export function startScreens(screensClasses)
}); });
_.each(SCREENS, (vmScreen) => { _.each(SCREENS, (vmScreen) => {
if (vmScreen && !vmScreen.__started && vmScreen.__start) if (vmScreen && !vmScreen.__started && vmScreen.__start) {
{
vmScreen.__started = true; vmScreen.__started = true;
vmScreen.__start(); vmScreen.__start();
@ -476,7 +426,7 @@ export function startScreens(screensClasses)
}); });
const cross = crossroads.create(); const cross = crossroads.create();
cross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, screenOnRoute); cross.addRoute(/^([a-zA-Z0-9-]*)\/?(.*)$/, screenOnRoute);
hasher.initialized.add(cross.parse, cross); hasher.initialized.add(cross.parse, cross);
hasher.changed.add(cross.parse, cross); hasher.changed.add(cross.parse, cross);
@ -492,21 +442,17 @@ export function startScreens(screensClasses)
* @param {boolean=} replace = false * @param {boolean=} replace = false
* @returns {void} * @returns {void}
*/ */
export function setHash(hash, silence = false, replace = false) export function setHash(hash, silence = false, replace = false) {
{
hash = '#' === hash.substr(0, 1) ? hash.substr(1) : hash; hash = '#' === hash.substr(0, 1) ? hash.substr(1) : hash;
hash = '/' === hash.substr(0, 1) ? hash.substr(1) : hash; hash = '/' === hash.substr(0, 1) ? hash.substr(1) : hash;
const cmd = replace ? 'replaceHash' : 'setHash'; const cmd = replace ? 'replaceHash' : 'setHash';
if (silence) if (silence) {
{
hasher.changed.active = false; hasher.changed.active = false;
hasher[cmd](hash); hasher[cmd](hash);
hasher.changed.active = true; hasher.changed.active = true;
} } else {
else
{
hasher.changed.active = true; hasher.changed.active = true;
hasher[cmd](hash); hasher[cmd](hash);
hasher.setHash(hash); hasher.setHash(hash);
@ -517,32 +463,24 @@ export function setHash(hash, silence = false, replace = false)
* @param {Object} params * @param {Object} params
* @returns {Function} * @returns {Function}
*/ */
function viewDecorator({name, type, templateID}) function viewDecorator({ name, type, templateID }) {
{
return (target) => { return (target) => {
if (target) if (target) {
{ if (name) {
if (name) if (isArray(name)) {
{
if (isArray(name))
{
target.__names = name; target.__names = name;
} } else {
else
{
target.__names = [name]; target.__names = [name];
} }
target.__name = target.__names[0]; target.__name = target.__names[0];
} }
if (type) if (type) {
{
target.__type = type; target.__type = type;
} }
if (templateID) if (templateID) {
{
target.__templateID = templateID; target.__templateID = templateID;
} }
} }
@ -553,31 +491,25 @@ function viewDecorator({name, type, templateID})
* @param {Object} params * @param {Object} params
* @returns {Function} * @returns {Function}
*/ */
function popupDecorator({name, templateID}) function popupDecorator({ name, templateID }) {
{ return viewDecorator({ name, type: ViewType.Popup, templateID });
return viewDecorator({name, type: ViewType.Popup, templateID});
} }
/** /**
* @param {Function} canExecute * @param {Function} canExecute
* @returns {Function} * @returns {Function}
*/ */
function commandDecorator(canExecute = true) function commandDecorator(canExecute = true) {
{
return (target, key, descriptor) => { return (target, key, descriptor) => {
if (!key || !key.match(/Command$/)) {
if (!key || !key.match(/Command$/))
{
throw new Error(`name "${key}" should end with Command suffix`); throw new Error(`name "${key}" should end with Command suffix`);
} }
const const value = descriptor.value || descriptor.initializer(),
value = descriptor.value || descriptor.initializer(),
normCanExecute = isFunc(canExecute) ? canExecute : () => !!canExecute; normCanExecute = isFunc(canExecute) ? canExecute : () => !!canExecute;
descriptor.value = function(...args) { descriptor.value = function(...args) {
if (normCanExecute.call(this, this)) if (normCanExecute.call(this, this)) {
{
value.apply(this, args); value.apply(this, args);
} }
@ -595,37 +527,33 @@ function commandDecorator(canExecute = true)
* @param {miced} $items * @param {miced} $items
* @returns {Function} * @returns {Function}
*/ */
function settingsMenuKeysHandler($items) function settingsMenuKeysHandler($items) {
{
return _.throttle((event, handler) => { return _.throttle((event, handler) => {
const up = handler && 'up' === handler.shortcut; const up = handler && 'up' === handler.shortcut;
if (event && $items.length) if (event && $items.length) {
{
let index = $items.index($items.filter('.selected')); let index = $items.index($items.filter('.selected'));
if (up && 0 < index) if (up && 0 < index) {
{
index -= 1; index -= 1;
} } else if (!up && index < $items.length - 1) {
else if (!up && index < $items.length - 1)
{
index += 1; index += 1;
} }
const resultHash = $items.eq(index).attr('href'); const resultHash = $items.eq(index).attr('href');
if (resultHash) if (resultHash) {
{
setHash(resultHash, false, true); setHash(resultHash, false, true);
} }
} }
}, Magics.Time200ms); }, Magics.Time200ms);
} }
export { export {
commandDecorator, commandDecorator as command, commandDecorator,
viewDecorator, viewDecorator as view, viewDecorator as viewModel, commandDecorator as command,
popupDecorator, popupDecorator as popup, viewDecorator,
viewDecorator as view,
viewDecorator as viewModel,
popupDecorator,
popupDecorator as popup,
settingsMenuKeysHandler settingsMenuKeysHandler
}; };

View file

@ -1,19 +1,16 @@
import ko from 'ko'; import ko from 'ko';
import {change} from 'Common/Links'; import { change } from 'Common/Links';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class AccountModel extends AbstractModel class AccountModel extends AbstractModel {
{
/** /**
* @param {string} email * @param {string} email
* @param {boolean=} canBeDelete = true * @param {boolean=} canBeDelete = true
* @param {number=} count = 0 * @param {number=} count = 0
*/ */
constructor(email, canBeDelete = true, count = 0) constructor(email, canBeDelete = true, count = 0) {
{
super('AccountModel'); super('AccountModel');
this.email = email; this.email = email;
@ -33,4 +30,4 @@ class AccountModel extends AbstractModel
} }
} }
export {AccountModel, AccountModel as default}; export { AccountModel, AccountModel as default };

View file

@ -1,14 +1,19 @@
import window from 'window'; import window from 'window';
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {FileType} from 'Common/Enums'; import { FileType } from 'Common/Enums';
import {bAllowPdfPreview, data as GlobalsData} from 'Common/Globals'; import { bAllowPdfPreview, data as GlobalsData } from 'Common/Globals';
import {trim, pInt, inArray, isNonEmptyArray, getFileExtension, friendlySize} from 'Common/Utils'; import { trim, pInt, inArray, isNonEmptyArray, getFileExtension, friendlySize } from 'Common/Utils';
import {attachmentDownload, attachmentPreview, attachmentFramed, attachmentPreviewAsPlain, attachmentThumbnailPreview} from 'Common/Links'; import {
attachmentDownload,
attachmentPreview,
attachmentFramed,
attachmentPreviewAsPlain,
attachmentThumbnailPreview
} from 'Common/Links';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
import Audio from 'Common/Audio'; import Audio from 'Common/Audio';
@ -24,90 +29,99 @@ export const staticFileType = _.memoize((ext, mimeType) => {
let result = FileType.Unknown; let result = FileType.Unknown;
const mimeTypeParts = mimeType.split('/'); const mimeTypeParts = mimeType.split('/');
switch (true) switch (true) {
{ case 'image' === mimeTypeParts[0] || -1 < inArray(ext, ['png', 'jpg', 'jpeg', 'gif', 'bmp']):
case 'image' === mimeTypeParts[0] || -1 < inArray(ext, [
'png', 'jpg', 'jpeg', 'gif', 'bmp'
]):
result = FileType.Image; result = FileType.Image;
break; break;
case 'audio' === mimeTypeParts[0] || -1 < inArray(ext, [ case 'audio' === mimeTypeParts[0] || -1 < inArray(ext, ['mp3', 'ogg', 'oga', 'wav']):
'mp3', 'ogg', 'oga', 'wav'
]):
result = FileType.Audio; result = FileType.Audio;
break; break;
case 'video' === mimeTypeParts[0] || -1 < inArray(ext, [ case 'video' === mimeTypeParts[0] || -1 < inArray(ext, ['mkv', 'avi']):
'mkv', 'avi'
]):
result = FileType.Video; result = FileType.Video;
break; break;
case -1 < inArray(ext, [ case -1 < inArray(ext, ['php', 'js', 'css']):
'php', 'js', 'css'
]):
result = FileType.Code; result = FileType.Code;
break; break;
case 'eml' === ext || -1 < inArray(mimeType, [ case 'eml' === ext || -1 < inArray(mimeType, ['message/delivery-status', 'message/rfc822']):
'message/delivery-status', 'message/rfc822'
]):
result = FileType.Eml; result = FileType.Eml;
break; break;
case ('text' === mimeTypeParts[0] && 'html' !== mimeTypeParts[1]) || -1 < inArray(ext, [ case ('text' === mimeTypeParts[0] && 'html' !== mimeTypeParts[1]) || -1 < inArray(ext, ['txt', 'log']):
'txt', 'log'
]):
result = FileType.Text; result = FileType.Text;
break; break;
case ('text/html' === mimeType) || -1 < inArray(ext, [ case 'text/html' === mimeType || -1 < inArray(ext, ['html']):
'html'
]):
result = FileType.Html; result = FileType.Html;
break; break;
case -1 < inArray(mimeTypeParts[1], [ case -1 <
'zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2', 'x-zip', 'x-7z', 'x-rar', 'x-tar', 'x-gzip', 'x-bzip', 'x-bzip2', 'x-zip-compressed', 'x-7z-compressed', 'x-rar-compressed' inArray(mimeTypeParts[1], [
]) || -1 < inArray(ext, ['zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2']): 'zip',
'7z',
'tar',
'rar',
'gzip',
'bzip',
'bzip2',
'x-zip',
'x-7z',
'x-rar',
'x-tar',
'x-gzip',
'x-bzip',
'x-bzip2',
'x-zip-compressed',
'x-7z-compressed',
'x-rar-compressed'
]) || -1 < inArray(ext, ['zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2']):
result = FileType.Archive; result = FileType.Archive;
break; break;
case -1 < inArray(mimeTypeParts[1], ['pdf', 'x-pdf']) || -1 < inArray(ext, ['pdf']): case -1 < inArray(mimeTypeParts[1], ['pdf', 'x-pdf']) || -1 < inArray(ext, ['pdf']):
result = FileType.Pdf; result = FileType.Pdf;
break; break;
case -1 < inArray(mimeType, [ case -1 < inArray(mimeType, ['application/pgp-signature', 'application/pgp-keys']) ||
'application/pgp-signature', 'application/pgp-keys' -1 < inArray(ext, ['asc', 'pem', 'ppk']):
]) || -1 < inArray(ext, ['asc', 'pem', 'ppk']):
result = FileType.Certificate; result = FileType.Certificate;
break; break;
case -1 < inArray(mimeType, ['application/pkcs7-signature']) || case -1 < inArray(mimeType, ['application/pkcs7-signature']) || -1 < inArray(ext, ['p7s']):
-1 < inArray(ext, ['p7s']):
result = FileType.CertificateBin; result = FileType.CertificateBin;
break; break;
case -1 < inArray(mimeTypeParts[1], [ case -1 <
'rtf', 'msword', 'vnd.msword', 'vnd.openxmlformats-officedocument.wordprocessingml.document', inArray(mimeTypeParts[1], [
'vnd.openxmlformats-officedocument.wordprocessingml.template', 'rtf',
'vnd.ms-word.document.macroEnabled.12', 'msword',
'vnd.ms-word.template.macroEnabled.12' 'vnd.msword',
]): 'vnd.openxmlformats-officedocument.wordprocessingml.document',
'vnd.openxmlformats-officedocument.wordprocessingml.template',
'vnd.ms-word.document.macroEnabled.12',
'vnd.ms-word.template.macroEnabled.12'
]):
result = FileType.WordText; result = FileType.WordText;
break; break;
case -1 < inArray(mimeTypeParts[1], [ case -1 <
'excel', 'ms-excel', 'vnd.ms-excel', inArray(mimeTypeParts[1], [
'vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'excel',
'vnd.openxmlformats-officedocument.spreadsheetml.template', 'ms-excel',
'vnd.ms-excel.sheet.macroEnabled.12', 'vnd.ms-excel',
'vnd.ms-excel.template.macroEnabled.12', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'vnd.ms-excel.addin.macroEnabled.12', 'vnd.openxmlformats-officedocument.spreadsheetml.template',
'vnd.ms-excel.sheet.binary.macroEnabled.12' 'vnd.ms-excel.sheet.macroEnabled.12',
]): 'vnd.ms-excel.template.macroEnabled.12',
'vnd.ms-excel.addin.macroEnabled.12',
'vnd.ms-excel.sheet.binary.macroEnabled.12'
]):
result = FileType.Sheet; result = FileType.Sheet;
break; break;
case -1 < inArray(mimeTypeParts[1], [ case -1 <
'powerpoint', 'ms-powerpoint', 'vnd.ms-powerpoint', inArray(mimeTypeParts[1], [
'vnd.openxmlformats-officedocument.presentationml.presentation', 'powerpoint',
'vnd.openxmlformats-officedocument.presentationml.template', 'ms-powerpoint',
'vnd.openxmlformats-officedocument.presentationml.slideshow', 'vnd.ms-powerpoint',
'vnd.ms-powerpoint.addin.macroEnabled.12', 'vnd.openxmlformats-officedocument.presentationml.presentation',
'vnd.ms-powerpoint.presentation.macroEnabled.12', 'vnd.openxmlformats-officedocument.presentationml.template',
'vnd.ms-powerpoint.template.macroEnabled.12', 'vnd.openxmlformats-officedocument.presentationml.slideshow',
'vnd.ms-powerpoint.slideshow.macroEnabled.12' 'vnd.ms-powerpoint.addin.macroEnabled.12',
]): 'vnd.ms-powerpoint.presentation.macroEnabled.12',
'vnd.ms-powerpoint.template.macroEnabled.12',
'vnd.ms-powerpoint.slideshow.macroEnabled.12'
]):
result = FileType.Presentation; result = FileType.Presentation;
break; break;
// no default // no default
@ -121,12 +135,10 @@ export const staticFileType = _.memoize((ext, mimeType) => {
* @returns {string} * @returns {string}
*/ */
export const staticIconClass = _.memoize((fileType) => { export const staticIconClass = _.memoize((fileType) => {
let let resultText = '',
resultText = '',
resultClass = 'icon-file'; resultClass = 'icon-file';
switch (fileType) switch (fileType) {
{
case FileType.Text: case FileType.Text:
case FileType.Eml: case FileType.Eml:
case FileType.WordText: case FileType.WordText:
@ -174,19 +186,15 @@ export const staticIconClass = _.memoize((fileType) => {
* @returns {string} * @returns {string}
*/ */
export const staticCombinedIconClass = (data) => { export const staticCombinedIconClass = (data) => {
let let result = '',
result = '',
types = []; types = [];
if (isNonEmptyArray(data)) if (isNonEmptyArray(data)) {
{
result = 'icon-attachment'; result = 'icon-attachment';
types = _.uniq(_.compact(_.map(data, (item) => (item ? staticFileType(getFileExtension(item[0]), item[1]) : '')))); types = _.uniq(_.compact(_.map(data, (item) => (item ? staticFileType(getFileExtension(item[0]), item[1]) : ''))));
if (types && 1 === types.length && types[0]) if (types && 1 === types.length && types[0]) {
{ switch (types[0]) {
switch (types[0])
{
case FileType.Text: case FileType.Text:
case FileType.WordText: case FileType.WordText:
result = 'icon-file-text'; result = 'icon-file-text';
@ -225,8 +233,7 @@ export const staticCombinedIconClass = (data) => {
return result; return result;
}; };
class AttachmentModel extends AbstractModel class AttachmentModel extends AbstractModel {
{
constructor() { constructor() {
super('AttachmentModel'); super('AttachmentModel');
@ -267,8 +274,7 @@ class AttachmentModel extends AbstractModel
*/ */
initByJson(json) { initByJson(json) {
let bResult = false; let bResult = false;
if (json && 'Object/Attachment' === json['@Object']) if (json && 'Object/Attachment' === json['@Object']) {
{
this.mimeType = trim((json.MimeType || '').toLowerCase()); this.mimeType = trim((json.MimeType || '').toLowerCase());
this.fileName = trim(json.FileName); this.fileName = trim(json.FileName);
this.estimatedSize = pInt(json.EstimatedSize); this.estimatedSize = pInt(json.EstimatedSize);
@ -335,8 +341,13 @@ class AttachmentModel extends AbstractModel
* @returns {boolean} * @returns {boolean}
*/ */
isText() { isText() {
return FileType.Text === this.fileType || FileType.Eml === this.fileType || return (
FileType.Certificate === this.fileType || FileType.Html === this.fileType || FileType.Code === this.fileType; FileType.Text === this.fileType ||
FileType.Eml === this.fileType ||
FileType.Certificate === this.fileType ||
FileType.Html === this.fileType ||
FileType.Code === this.fileType
);
} }
/** /**
@ -350,8 +361,13 @@ class AttachmentModel extends AbstractModel
* @returns {boolean} * @returns {boolean}
*/ */
isFramed() { isFramed() {
return this.framed && (GlobalsData.__APP__ && GlobalsData.__APP__.googlePreviewSupported()) && return (
!(this.isPdf() && bAllowPdfPreview) && !this.isText() && !this.isImage(); this.framed &&
(GlobalsData.__APP__ && GlobalsData.__APP__.googlePreviewSupported()) &&
!(this.isPdf() && bAllowPdfPreview) &&
!this.isText() &&
!this.isImage()
);
} }
/** /**
@ -365,7 +381,11 @@ class AttachmentModel extends AbstractModel
* @returns {boolean} * @returns {boolean}
*/ */
hasPreplay() { hasPreplay() {
return (Audio.supportedMp3 && this.isMp3()) || (Audio.supportedOgg && this.isOgg()) || (Audio.supportedWav && this.isWav()); return (
(Audio.supportedMp3 && this.isMp3()) ||
(Audio.supportedOgg && this.isOgg()) ||
(Audio.supportedWav && this.isWav())
);
} }
/** /**
@ -416,8 +436,7 @@ class AttachmentModel extends AbstractModel
*/ */
linkPreviewMain() { linkPreviewMain() {
let result = ''; let result = '';
switch (true) switch (true) {
{
case this.isImage(): case this.isImage():
case this.isPdf() && bAllowPdfPreview: case this.isPdf() && bAllowPdfPreview:
result = this.linkPreview(); result = this.linkPreview();
@ -439,8 +458,7 @@ class AttachmentModel extends AbstractModel
*/ */
generateTransferDownloadUrl() { generateTransferDownloadUrl() {
let link = this.linkDownload(); let link = this.linkDownload();
if ('http' !== link.substr(0, 4)) if ('http' !== link.substr(0, 4)) {
{
link = window.location.protocol + '//' + window.location.host + window.location.pathname + link; link = window.location.protocol + '//' + window.location.host + window.location.pathname + link;
} }
@ -454,8 +472,7 @@ class AttachmentModel extends AbstractModel
*/ */
eventDragStart(attachment, event) { eventDragStart(attachment, event) {
const localEvent = event.originalEvent || event; const localEvent = event.originalEvent || event;
if (attachment && localEvent && localEvent.dataTransfer && localEvent.dataTransfer.setData) if (attachment && localEvent && localEvent.dataTransfer && localEvent.dataTransfer.setData) {
{
localEvent.dataTransfer.setData('DownloadURL', this.generateTransferDownloadUrl()); localEvent.dataTransfer.setData('DownloadURL', this.generateTransferDownloadUrl());
} }
@ -477,4 +494,4 @@ class AttachmentModel extends AbstractModel
} }
} }
export {AttachmentModel, AttachmentModel as default}; export { AttachmentModel, AttachmentModel as default };

View file

@ -1,12 +1,10 @@
import ko from 'ko'; import ko from 'ko';
import {isUnd, pInt, friendlySize, mimeContentType, getFileExtension} from 'Common/Utils'; import { isUnd, pInt, friendlySize, mimeContentType, getFileExtension } from 'Common/Utils';
import {staticIconClass, staticFileType} from 'Model/Attachment'; import { staticIconClass, staticFileType } from 'Model/Attachment';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class ComposeAttachmentModel extends AbstractModel class ComposeAttachmentModel extends AbstractModel {
{
/** /**
* @param {string} id * @param {string} id
* @param {string} fileName * @param {string} fileName
@ -16,8 +14,7 @@ class ComposeAttachmentModel extends AbstractModel
* @param {string=} CID = '' * @param {string=} CID = ''
* @param {string=} contentLocation = '' * @param {string=} contentLocation = ''
*/ */
constructor(id, fileName, size = null, isInline = false, isLinked = false, CID = '', contentLocation = '') constructor(id, fileName, size = null, isInline = false, isLinked = false, CID = '', contentLocation = '') {
{
super('ComposeAttachmentModel'); super('ComposeAttachmentModel');
this.id = id; this.id = id;
@ -61,7 +58,14 @@ class ComposeAttachmentModel extends AbstractModel
this.mimeType = ko.computed(() => mimeContentType(this.fileName())); this.mimeType = ko.computed(() => mimeContentType(this.fileName()));
this.fileExt = ko.computed(() => getFileExtension(this.fileName())); this.fileExt = ko.computed(() => getFileExtension(this.fileName()));
this.regDisposables([this.progressText, this.progressStyle, this.title, this.friendlySize, this.mimeType, this.fileExt]); this.regDisposables([
this.progressText,
this.progressStyle,
this.title,
this.friendlySize,
this.mimeType,
this.fileExt
]);
} }
/** /**
@ -70,8 +74,7 @@ class ComposeAttachmentModel extends AbstractModel
*/ */
initByUploadJson(json) { initByUploadJson(json) {
let bResult = false; let bResult = false;
if (json) if (json) {
{
this.fileName(json.Name); this.fileName(json.Name);
this.size(isUnd(json.Size) ? 0 : pInt(json.Size)); this.size(isUnd(json.Size) ? 0 : pInt(json.Size));
this.tempName(isUnd(json.TempName) ? '' : json.TempName); this.tempName(isUnd(json.TempName) ? '' : json.TempName);
@ -98,4 +101,4 @@ class ComposeAttachmentModel extends AbstractModel
} }
} }
export {ComposeAttachmentModel, ComposeAttachmentModel as default}; export { ComposeAttachmentModel, ComposeAttachmentModel as default };

View file

@ -1,15 +1,13 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {ContactPropertyType} from 'Common/Enums'; import { ContactPropertyType } from 'Common/Enums';
import {trim, isNonEmptyArray, isNormal, pInt, pString} from 'Common/Utils'; import { trim, isNonEmptyArray, isNormal, pInt, pString } from 'Common/Utils';
import {emptyContactPic} from 'Common/Links'; import { emptyContactPic } from 'Common/Links';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class ContactModel extends AbstractModel class ContactModel extends AbstractModel {
{
constructor() { constructor() {
super('ContactModel'); super('ContactModel');
@ -28,25 +26,17 @@ class ContactModel extends AbstractModel
* @returns {Array|null} * @returns {Array|null}
*/ */
getNameAndEmailHelper() { getNameAndEmailHelper() {
let let name = '',
name = '',
email = ''; email = '';
if (isNonEmptyArray(this.properties)) if (isNonEmptyArray(this.properties)) {
{
_.each(this.properties, (property) => { _.each(this.properties, (property) => {
if (property) if (property) {
{ if (ContactPropertyType.FirstName === property[0]) {
if (ContactPropertyType.FirstName === property[0])
{
name = trim(property[1] + ' ' + name); name = trim(property[1] + ' ' + name);
} } else if (ContactPropertyType.LastName === property[0]) {
else if (ContactPropertyType.LastName === property[0])
{
name = trim(name + ' ' + property[1]); name = trim(name + ' ' + property[1]);
} } else if ('' === email && ContactPropertyType.Email === property[0]) {
else if ('' === email && ContactPropertyType.Email === property[0])
{
email = property[1]; email = property[1];
} }
} }
@ -62,17 +52,14 @@ class ContactModel extends AbstractModel
*/ */
parse(json) { parse(json) {
let result = false; let result = false;
if (json && 'Object/Contact' === json['@Object']) if (json && 'Object/Contact' === json['@Object']) {
{
this.idContact = pInt(json.IdContact); this.idContact = pInt(json.IdContact);
this.display = pString(json.Display); this.display = pString(json.Display);
this.readOnly = !!json.ReadOnly; this.readOnly = !!json.ReadOnly;
if (isNonEmptyArray(json.Properties)) if (isNonEmptyArray(json.Properties)) {
{
_.each(json.Properties, (property) => { _.each(json.Properties, (property) => {
if (property && property.Type && isNormal(property.Value) && isNormal(property.TypeStr)) if (property && property.Type && isNormal(property.Value) && isNormal(property.TypeStr)) {
{
this.properties.push([pInt(property.Type), pString(property.Value), pString(property.TypeStr)]); this.properties.push([pInt(property.Type), pString(property.Value), pString(property.TypeStr)]);
} }
}); });
@ -103,20 +90,16 @@ class ContactModel extends AbstractModel
*/ */
lineAsCss() { lineAsCss() {
const result = []; const result = [];
if (this.deleted()) if (this.deleted()) {
{
result.push('deleted'); result.push('deleted');
} }
if (this.selected()) if (this.selected()) {
{
result.push('selected'); result.push('selected');
} }
if (this.checked()) if (this.checked()) {
{
result.push('checked'); result.push('checked');
} }
if (this.focused()) if (this.focused()) {
{
result.push('focused'); result.push('focused');
} }
@ -124,4 +107,4 @@ class ContactModel extends AbstractModel
} }
} }
export {ContactModel, ContactModel as default}; export { ContactModel, ContactModel as default };

View file

@ -1,14 +1,12 @@
import ko from 'ko'; import ko from 'ko';
import {ContactPropertyType} from 'Common/Enums'; import { ContactPropertyType } from 'Common/Enums';
import {pInt, pString} from 'Common/Utils'; import { pInt, pString } from 'Common/Utils';
import {i18n} from 'Common/Translator'; import { i18n } from 'Common/Translator';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class ContactPropertyModel extends AbstractModel class ContactPropertyModel extends AbstractModel {
{
/** /**
* @param {number=} type = Enums.ContactPropertyType.Unknown * @param {number=} type = Enums.ContactPropertyType.Unknown
* @param {string=} typeStr = '' * @param {string=} typeStr = ''
@ -16,8 +14,7 @@ class ContactPropertyModel extends AbstractModel
* @param {boolean=} focused = false * @param {boolean=} focused = false
* @param {string=} placeholder = '' * @param {string=} placeholder = ''
*/ */
constructor(type = ContactPropertyType.Unknown, typeStr = '', value = '', focused = false, placeholder = '') constructor(type = ContactPropertyType.Unknown, typeStr = '', value = '', focused = false, placeholder = '') {
{
super('ContactPropertyModel'); super('ContactPropertyModel');
this.type = ko.observable(pInt(type)); this.type = ko.observable(pInt(type));
@ -38,4 +35,4 @@ class ContactPropertyModel extends AbstractModel
} }
} }
export {ContactPropertyModel, ContactPropertyModel as default}; export { ContactPropertyModel, ContactPropertyModel as default };

View file

@ -1,10 +1,8 @@
import _ from '_'; import _ from '_';
import addressparser from 'emailjs-addressparser'; import addressparser from 'emailjs-addressparser';
import {trim, encodeHtml, isNonEmptyArray} from 'Common/Utils'; import { trim, encodeHtml, isNonEmptyArray } from 'Common/Utils';
class EmailModel class EmailModel {
{
email = ''; email = '';
name = ''; name = '';
dkimStatus = ''; dkimStatus = '';
@ -16,8 +14,7 @@ class EmailModel
* @param {string=} dkimStatus = 'none' * @param {string=} dkimStatus = 'none'
* @param {string=} dkimValue = '' * @param {string=} dkimValue = ''
*/ */
constructor(email = '', name = '', dkimStatus = 'none', dkimValue = '') constructor(email = '', name = '', dkimStatus = 'none', dkimValue = '') {
{
this.email = email; this.email = email;
this.name = name; this.name = name;
this.dkimStatus = dkimStatus; this.dkimStatus = dkimStatus;
@ -66,8 +63,7 @@ class EmailModel
* @returns {void} * @returns {void}
*/ */
clearDuplicateName() { clearDuplicateName() {
if (this.name === this.email) if (this.name === this.email) {
{
this.name = ''; this.name = '';
} }
} }
@ -86,8 +82,7 @@ class EmailModel
*/ */
initByJson(json) { initByJson(json) {
let result = false; let result = false;
if (json && 'Object/Email' === json['@Object']) if (json && 'Object/Email' === json['@Object']) {
{
this.name = trim(json.Name); this.name = trim(json.Name);
this.email = trim(json.Email); this.email = trim(json.Email);
this.dkimStatus = trim(json.DkimStatus || ''); this.dkimStatus = trim(json.DkimStatus || '');
@ -108,24 +103,31 @@ class EmailModel
*/ */
toLine(friendlyView, wrapWithLink = false, useEncodeHtml = false) { toLine(friendlyView, wrapWithLink = false, useEncodeHtml = false) {
let result = ''; let result = '';
if ('' !== this.email) if ('' !== this.email) {
{ if (friendlyView && '' !== this.name) {
if (friendlyView && '' !== this.name) result = wrapWithLink
{ ? '<a href="mailto:' +
result = wrapWithLink ? '<a href="mailto:' + encodeHtml(this.email) + '?to=' + encodeHtml('"' + this.name + '" <' + this.email + '>') + encodeHtml(this.email) +
'" target="_blank" tabindex="-1">' + encodeHtml(this.name) + '</a>' : (useEncodeHtml ? encodeHtml(this.name) : this.name); '?to=' +
encodeHtml('"' + this.name + '" <' + this.email + '>') +
'" target="_blank" tabindex="-1">' +
encodeHtml(this.name) +
'</a>'
: useEncodeHtml
? encodeHtml(this.name)
: this.name;
// result = wrapWithLink ? '<a href="mailto:' + encodeHtml('"' + this.name + '" <' + this.email + '>') + // result = wrapWithLink ? '<a href="mailto:' + encodeHtml('"' + this.name + '" <' + this.email + '>') +
// '" target="_blank" tabindex="-1">' + encodeHtml(this.name) + '</a>' : (useEncodeHtml ? encodeHtml(this.name) : this.name); // '" target="_blank" tabindex="-1">' + encodeHtml(this.name) + '</a>' : (useEncodeHtml ? encodeHtml(this.name) : this.name);
} } else {
else
{
result = this.email; result = this.email;
if ('' !== this.name) if ('' !== this.name) {
{ if (wrapWithLink) {
if (wrapWithLink) result =
{ encodeHtml('"' + this.name + '" <') +
result = encodeHtml('"' + this.name + '" <') + '<a href="mailto:' + '<a href="mailto:' +
encodeHtml(this.email) + '?to=' + encodeHtml('"' + this.name + '" <' + this.email + '>') + encodeHtml(this.email) +
'?to=' +
encodeHtml('"' + this.name + '" <' + this.email + '>') +
'" target="_blank" tabindex="-1">' + '" target="_blank" tabindex="-1">' +
encodeHtml(result) + encodeHtml(result) +
'</a>' + '</a>' +
@ -136,19 +138,19 @@ class EmailModel
// encodeHtml(result) + // encodeHtml(result) +
// '</a>' + // '</a>' +
// encodeHtml('>'); // encodeHtml('>');
} } else {
else
{
result = '"' + this.name + '" <' + result + '>'; result = '"' + this.name + '" <' + result + '>';
if (useEncodeHtml) if (useEncodeHtml) {
{
result = encodeHtml(result); result = encodeHtml(result);
} }
} }
} } else if (wrapWithLink) {
else if (wrapWithLink) result =
{ '<a href="mailto:' +
result = '<a href="mailto:' + encodeHtml(this.email) + '" target="_blank" tabindex="-1">' + encodeHtml(this.email) + '</a>'; encodeHtml(this.email) +
'" target="_blank" tabindex="-1">' +
encodeHtml(this.email) +
'</a>';
} }
} }
} }
@ -158,15 +160,13 @@ class EmailModel
static splitEmailLine(line) { static splitEmailLine(line) {
const parsedResult = addressparser(line); const parsedResult = addressparser(line);
if (isNonEmptyArray(parsedResult)) if (isNonEmptyArray(parsedResult)) {
{
const result = []; const result = [];
let exists = false; let exists = false;
parsedResult.forEach((item) => { parsedResult.forEach((item) => {
const address = item.address ? new EmailModel( const address = item.address
item.address.replace(/^[<]+(.*)[>]+$/g, '$1'), ? new EmailModel(item.address.replace(/^[<]+(.*)[>]+$/g, '$1'), item.name || '')
item.name || '' : null;
) : null;
if (address && address.email) { if (address && address.email) {
exists = true; exists = true;
@ -183,14 +183,12 @@ class EmailModel
static parseEmailLine(line) { static parseEmailLine(line) {
const parsedResult = addressparser(line); const parsedResult = addressparser(line);
if (isNonEmptyArray(parsedResult)) if (isNonEmptyArray(parsedResult)) {
{ return _.compact(
return _.compact(parsedResult.map( parsedResult.map((item) =>
(item) => (item.address ? new EmailModel( item.address ? new EmailModel(item.address.replace(/^[<]+(.*)[>]+$/g, '$1'), item.name || '') : null
item.address.replace(/^[<]+(.*)[>]+$/g, '$1'), )
item.name || '' );
) : null)
));
} }
return []; return [];
@ -202,14 +200,12 @@ class EmailModel
*/ */
parse(emailAddress) { parse(emailAddress) {
emailAddress = trim(emailAddress); emailAddress = trim(emailAddress);
if ('' === emailAddress) if ('' === emailAddress) {
{
return false; return false;
} }
const result = addressparser(emailAddress); const result = addressparser(emailAddress);
if (isNonEmptyArray(result) && result[0]) if (isNonEmptyArray(result) && result[0]) {
{
this.name = result[0].name || ''; this.name = result[0].name || '';
this.email = result[0].address || ''; this.email = result[0].address || '';
this.clearDuplicateName(); this.clearDuplicateName();
@ -221,4 +217,4 @@ class EmailModel
} }
} }
export {EmailModel, EmailModel as default}; export { EmailModel, EmailModel as default };

View file

@ -1,19 +1,17 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {FilterRulesType, FiltersAction} from 'Common/Enums'; import { FilterRulesType, FiltersAction } from 'Common/Enums';
import {pString, inArray, isNonEmptyArray, fakeMd5, delegateRunOnDestroy, windowResizeCallback} from 'Common/Utils'; import { pString, inArray, isNonEmptyArray, fakeMd5, delegateRunOnDestroy, windowResizeCallback } from 'Common/Utils';
import {i18n} from 'Common/Translator'; import { i18n } from 'Common/Translator';
import {getFolderFromCacheList} from 'Common/Cache'; import { getFolderFromCacheList } from 'Common/Cache';
import AccountStore from 'Stores/User/Account'; import AccountStore from 'Stores/User/Account';
import {FilterConditionModel} from 'Model/FilterCondition'; import { FilterConditionModel } from 'Model/FilterCondition';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class FilterModel extends AbstractModel class FilterModel extends AbstractModel {
{
constructor() { constructor() {
super('FilterModel'); super('FilterModel');
@ -56,15 +54,14 @@ class FilterModel extends AbstractModel
const fGetRealFolderName = (folderFullNameRaw) => { const fGetRealFolderName = (folderFullNameRaw) => {
const folder = getFolderFromCacheList(folderFullNameRaw); const folder = getFolderFromCacheList(folderFullNameRaw);
return folder ? folder.fullName.replace('.' === folder.delimiter ? /\./ : /[\\\/]+/, ' / ') : folderFullNameRaw; return folder ? folder.fullName.replace('.' === folder.delimiter ? /\./ : /[\\/]+/, ' / ') : folderFullNameRaw;
}; };
this.nameSub = ko.computed(() => { this.nameSub = ko.computed(() => {
let result = ''; let result = '';
const actionValue = this.actionValue(); const actionValue = this.actionValue();
switch (this.actionType()) switch (this.actionType()) {
{
case FiltersAction.MoveTo: case FiltersAction.MoveTo:
result = i18n('SETTINGS_FILTERS/SUBNAME_MOVE_TO', { result = i18n('SETTINGS_FILTERS/SUBNAME_MOVE_TO', {
FOLDER: fGetRealFolderName(actionValue) FOLDER: fGetRealFolderName(actionValue)
@ -93,8 +90,7 @@ class FilterModel extends AbstractModel
this.actionTemplate = ko.computed(() => { this.actionTemplate = ko.computed(() => {
let result = ''; let result = '';
switch (this.actionType()) switch (this.actionType()) {
{
case FiltersAction.Forward: case FiltersAction.Forward:
result = 'SettingsFiltersActionForward'; result = 'SettingsFiltersActionForward';
break; break;
@ -121,13 +117,17 @@ class FilterModel extends AbstractModel
this.regDisposables(this.conditions.subscribe(windowResizeCallback)); this.regDisposables(this.conditions.subscribe(windowResizeCallback));
this.regDisposables(this.name.subscribe((sValue) => { this.regDisposables(
this.name.error('' === sValue); this.name.subscribe((sValue) => {
})); this.name.error('' === sValue);
})
);
this.regDisposables(this.actionValue.subscribe((sValue) => { this.regDisposables(
this.actionValue.error('' === sValue); this.actionValue.subscribe((sValue) => {
})); this.actionValue.error('' === sValue);
})
);
this.regDisposables([this.actionNoStop, this.actionTemplate]); this.regDisposables([this.actionNoStop, this.actionTemplate]);
@ -140,42 +140,42 @@ class FilterModel extends AbstractModel
} }
verify() { verify() {
if ('' === this.name()) if ('' === this.name()) {
{
this.name.error(true); this.name.error(true);
return false; return false;
} }
if (0 < this.conditions().length) if (0 < this.conditions().length) {
{ if (_.find(this.conditions(), (cond) => cond && !cond.verify())) {
if (_.find(this.conditions(), (cond) => cond && !cond.verify()))
{
return false; return false;
} }
} }
if ('' === this.actionValue()) if ('' === this.actionValue()) {
{ if (
if (-1 < inArray(this.actionType(), [ -1 <
FiltersAction.MoveTo, FiltersAction.Forward, FiltersAction.Reject, FiltersAction.Vacation inArray(this.actionType(), [
])) FiltersAction.MoveTo,
{ FiltersAction.Forward,
FiltersAction.Reject,
FiltersAction.Vacation
])
) {
this.actionValue.error(true); this.actionValue.error(true);
return false; return false;
} }
} }
if (FiltersAction.Forward === this.actionType() && if (FiltersAction.Forward === this.actionType() && -1 === this.actionValue().indexOf('@')) {
-1 === this.actionValue().indexOf('@'))
{
this.actionValue.error(true); this.actionValue.error(true);
return false; return false;
} }
if (FiltersAction.Vacation === this.actionType() && if (
'' !== this.actionValueFourth() && -1 === this.actionValueFourth().indexOf('@') FiltersAction.Vacation === this.actionType() &&
) '' !== this.actionValueFourth() &&
{ -1 === this.actionValueFourth().indexOf('@')
) {
this.actionValueFourth.error(true); this.actionValueFourth.error(true);
return false; return false;
} }
@ -221,8 +221,7 @@ class FilterModel extends AbstractModel
parse(json) { parse(json) {
let result = false; let result = false;
if (json && 'Object/Filter' === json['@Object']) if (json && 'Object/Filter' === json['@Object']) {
{
this.id = pString(json.ID); this.id = pString(json.ID);
this.name(pString(json.Name)); this.name(pString(json.Name));
this.enabled(!!json.Enabled); this.enabled(!!json.Enabled);
@ -231,12 +230,15 @@ class FilterModel extends AbstractModel
this.conditions([]); this.conditions([]);
if (isNonEmptyArray(json.Conditions)) if (isNonEmptyArray(json.Conditions)) {
{ this.conditions(
this.conditions(_.compact(_.map(json.Conditions, (aData) => { _.compact(
const filterCondition = new FilterConditionModel(); _.map(json.Conditions, (aData) => {
return filterCondition && filterCondition.parse(aData) ? filterCondition : null; const filterCondition = new FilterConditionModel();
}))); return filterCondition && filterCondition.parse(aData) ? filterCondition : null;
})
)
);
} }
this.actionType(pString(json.ActionType)); this.actionType(pString(json.ActionType));
@ -257,7 +259,6 @@ class FilterModel extends AbstractModel
} }
cloneSelf() { cloneSelf() {
const filter = new FilterModel(); const filter = new FilterModel();
filter.id = this.id; filter.id = this.id;
@ -289,4 +290,4 @@ class FilterModel extends AbstractModel
} }
} }
export {FilterModel, FilterModel as default}; export { FilterModel, FilterModel as default };

View file

@ -1,13 +1,11 @@
import ko from 'ko'; import ko from 'ko';
import {FilterConditionField, FilterConditionType} from 'Common/Enums'; import { FilterConditionField, FilterConditionType } from 'Common/Enums';
import {pString} from 'Common/Utils'; import { pString } from 'Common/Utils';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class FilterConditionModel extends AbstractModel class FilterConditionModel extends AbstractModel {
{
constructor() { constructor() {
super('FilterConditionModel'); super('FilterConditionModel');
@ -20,10 +18,8 @@ class FilterConditionModel extends AbstractModel
this.valueSecond.error = ko.observable(false); this.valueSecond.error = ko.observable(false);
this.template = ko.computed(() => { this.template = ko.computed(() => {
let template = ''; let template = '';
switch (this.field()) switch (this.field()) {
{
case FilterConditionField.Size: case FilterConditionField.Size:
template = 'SettingsFiltersConditionSize'; template = 'SettingsFiltersConditionSize';
break; break;
@ -36,7 +32,6 @@ class FilterConditionModel extends AbstractModel
} }
return template; return template;
}, this); }, this);
this.field.subscribe(() => { this.field.subscribe(() => {
@ -48,14 +43,12 @@ class FilterConditionModel extends AbstractModel
} }
verify() { verify() {
if ('' === this.value()) if ('' === this.value()) {
{
this.value.error(true); this.value.error(true);
return false; return false;
} }
if (FilterConditionField.Header === this.field() && '' === this.valueSecond()) if (FilterConditionField.Header === this.field() && '' === this.valueSecond()) {
{
this.valueSecond.error(true); this.valueSecond.error(true);
return false; return false;
} }
@ -64,8 +57,7 @@ class FilterConditionModel extends AbstractModel
} }
parse(json) { parse(json) {
if (json && json.Field && json.Type) if (json && json.Field && json.Type) {
{
this.field(pString(json.Field)); this.field(pString(json.Field));
this.type(pString(json.Type)); this.type(pString(json.Type));
this.value(pString(json.Value)); this.value(pString(json.Value));
@ -98,4 +90,4 @@ class FilterConditionModel extends AbstractModel
} }
} }
export {FilterConditionModel, FilterConditionModel as default}; export { FilterConditionModel, FilterConditionModel as default };

View file

@ -1,17 +1,15 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {FolderType} from 'Common/Enums'; import { FolderType } from 'Common/Enums';
import {isPosNumeric} from 'Common/Utils'; import { isPosNumeric } from 'Common/Utils';
import {i18n, trigger as translatorTrigger} from 'Common/Translator'; import { i18n, trigger as translatorTrigger } from 'Common/Translator';
import {getFolderInboxName} from 'Common/Cache'; import { getFolderInboxName } from 'Common/Cache';
import * as Events from 'Common/Events'; import * as Events from 'Common/Events';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class FolderModel extends AbstractModel class FolderModel extends AbstractModel {
{
constructor() { constructor() {
super('FolderModel'); super('FolderModel');
@ -36,7 +34,7 @@ class FolderModel extends AbstractModel
this.checkable = ko.observable(false); this.checkable = ko.observable(false);
this.subFolders = ko.observableArray([]); this.subFolders = ko.observableArray([]);
this.deleteAccess = ko.observable(false); this.deleteAccess = ko.observable(false);
this.actionBlink = ko.observable(false).extend({falseTimeout: 1000}); this.actionBlink = ko.observable(false).extend({ falseTimeout: 1000 });
this.nameForEdit = ko.observable(''); this.nameForEdit = ko.observable('');
@ -65,24 +63,26 @@ class FolderModel extends AbstractModel
this.isInbox = ko.computed(() => FolderType.Inbox === this.type()); this.isInbox = ko.computed(() => FolderType.Inbox === this.type());
this.hasSubScribedSubfolders = ko.computed( this.hasSubScribedSubfolders = ko.computed(
() => !!_.find(this.subFolders(), (oFolder) => (oFolder.subScribed() || oFolder.hasSubScribedSubfolders()) && !oFolder.isSystemFolder()) () =>
!!_.find(
this.subFolders(),
(oFolder) => (oFolder.subScribed() || oFolder.hasSubScribedSubfolders()) && !oFolder.isSystemFolder()
)
); );
this.canBeEdited = ko.computed(() => FolderType.User === this.type() && this.existen && this.selectable); this.canBeEdited = ko.computed(() => FolderType.User === this.type() && this.existen && this.selectable);
this.visible = ko.computed(() => { this.visible = ko.computed(() => {
const const isSubScribed = this.subScribed(),
isSubScribed = this.subScribed(),
isSubFolders = this.hasSubScribedSubfolders(); isSubFolders = this.hasSubScribedSubfolders();
return (isSubScribed || (isSubFolders && (!this.existen || !this.selectable))); return isSubScribed || (isSubFolders && (!this.existen || !this.selectable));
}); });
this.isSystemFolder = ko.computed(() => FolderType.User !== this.type()); this.isSystemFolder = ko.computed(() => FolderType.User !== this.type());
this.hidden = ko.computed(() => { this.hidden = ko.computed(() => {
const const isSystem = this.isSystemFolder(),
isSystem = this.isSystemFolder(),
isSubFolders = this.hasSubScribedSubfolders(); isSubFolders = this.hasSubScribedSubfolders();
return (isSystem && !isSubFolders) || (!this.selectable && !isSubFolders); return (isSystem && !isSubFolders) || (!this.selectable && !isSubFolders);
@ -90,48 +90,46 @@ class FolderModel extends AbstractModel
this.selectableForFolderList = ko.computed(() => !this.isSystemFolder() && this.selectable); this.selectableForFolderList = ko.computed(() => !this.isSystemFolder() && this.selectable);
this.messageCountAll = ko.computed({ this.messageCountAll = ko
read: this.privateMessageCountAll, .computed({
write: (iValue) => { read: this.privateMessageCountAll,
if (isPosNumeric(iValue, true)) write: (iValue) => {
{ if (isPosNumeric(iValue, true)) {
this.privateMessageCountAll(iValue); this.privateMessageCountAll(iValue);
} else {
this.privateMessageCountAll.valueHasMutated();
}
} }
else })
{ .extend({ notify: 'always' });
this.privateMessageCountAll.valueHasMutated();
}
}
}).extend({notify: 'always'});
this.messageCountUnread = ko.computed({ this.messageCountUnread = ko
read: this.privateMessageCountUnread, .computed({
write: (value) => { read: this.privateMessageCountUnread,
if (isPosNumeric(value, true)) write: (value) => {
{ if (isPosNumeric(value, true)) {
this.privateMessageCountUnread(value); this.privateMessageCountUnread(value);
} else {
this.privateMessageCountUnread.valueHasMutated();
}
} }
else })
{ .extend({ notify: 'always' });
this.privateMessageCountUnread.valueHasMutated();
}
}
}).extend({notify: 'always'});
this.printableUnreadCount = ko.computed(() => { this.printableUnreadCount = ko.computed(() => {
const const count = this.messageCountAll(),
count = this.messageCountAll(),
unread = this.messageCountUnread(), unread = this.messageCountUnread(),
type = this.type(); type = this.type();
if (0 < count) if (0 < count) {
{ if (FolderType.Draft === type) {
if (FolderType.Draft === type)
{
return '' + count; return '' + count;
} } else if (
else if (0 < unread && FolderType.Trash !== type && FolderType.Archive !== type && FolderType.SentItems !== type) 0 < unread &&
{ FolderType.Trash !== type &&
FolderType.Archive !== type &&
FolderType.SentItems !== type
) {
return '' + unread; return '' + unread;
} }
} }
@ -144,21 +142,20 @@ class FolderModel extends AbstractModel
return !bSystem && 0 === this.subFolders().length && inboxFolderName !== this.fullNameRaw; return !bSystem && 0 === this.subFolders().length && inboxFolderName !== this.fullNameRaw;
}); });
this.canBeSubScribed = ko.computed(() => !this.isSystemFolder() && this.selectable && inboxFolderName !== this.fullNameRaw); this.canBeSubScribed = ko.computed(
() => !this.isSystemFolder() && this.selectable && inboxFolderName !== this.fullNameRaw
);
this.canBeChecked = this.canBeSubScribed; this.canBeChecked = this.canBeSubScribed;
this.localName = ko.computed(() => { this.localName = ko.computed(() => {
translatorTrigger(); translatorTrigger();
let name = this.name(); let name = this.name();
const type = this.type(); const type = this.type();
if (this.isSystemFolder()) if (this.isSystemFolder()) {
{ switch (type) {
switch (type)
{
case FolderType.Inbox: case FolderType.Inbox:
name = i18n('FOLDER_LIST/INBOX_NAME'); name = i18n('FOLDER_LIST/INBOX_NAME');
break; break;
@ -185,18 +182,14 @@ class FolderModel extends AbstractModel
}); });
this.manageFolderSystemName = ko.computed(() => { this.manageFolderSystemName = ko.computed(() => {
translatorTrigger(); translatorTrigger();
let suffix = ''; let suffix = '';
const const type = this.type(),
type = this.type(),
name = this.name(); name = this.name();
if (this.isSystemFolder()) if (this.isSystemFolder()) {
{ switch (type) {
switch (type)
{
case FolderType.Inbox: case FolderType.Inbox:
suffix = '(' + i18n('FOLDER_LIST/INBOX_NAME') + ')'; suffix = '(' + i18n('FOLDER_LIST/INBOX_NAME') + ')';
break; break;
@ -219,8 +212,7 @@ class FolderModel extends AbstractModel
} }
} }
if ('' !== suffix && '(' + name + ')' === suffix || '(inbox)' === suffix.toLowerCase()) if (('' !== suffix && '(' + name + ')' === suffix) || '(inbox)' === suffix.toLowerCase()) {
{
suffix = ''; suffix = '';
} }
@ -237,7 +229,11 @@ class FolderModel extends AbstractModel
this.hasUnreadMessages = ko.computed(() => 0 < this.messageCountUnread() && '' !== this.printableUnreadCount()); this.hasUnreadMessages = ko.computed(() => 0 < this.messageCountUnread() && '' !== this.printableUnreadCount());
this.hasSubScribedUnreadMessagesSubfolders = ko.computed( this.hasSubScribedUnreadMessagesSubfolders = ko.computed(
() => !!_.find(this.subFolders(), (folder) => folder.hasUnreadMessages() || folder.hasSubScribedUnreadMessagesSubfolders()) () =>
!!_.find(
this.subFolders(),
(folder) => folder.hasUnreadMessages() || folder.hasSubScribedUnreadMessagesSubfolders()
)
); );
// subscribe // subscribe
@ -246,15 +242,13 @@ class FolderModel extends AbstractModel
}); });
this.edited.subscribe((value) => { this.edited.subscribe((value) => {
if (value) if (value) {
{
this.nameForEdit(this.name()); this.nameForEdit(this.name());
} }
}); });
this.messageCountUnread.subscribe((unread) => { this.messageCountUnread.subscribe((unread) => {
if (FolderType.Inbox === this.type()) if (FolderType.Inbox === this.type()) {
{
Events.pub('mailbox.inbox-unread-count', [unread]); Events.pub('mailbox.inbox-unread-count', [unread]);
} }
}); });
@ -266,8 +260,11 @@ class FolderModel extends AbstractModel
* @returns {string} * @returns {string}
*/ */
collapsedCss() { collapsedCss() {
return this.hasSubScribedSubfolders() ? return this.hasSubScribedSubfolders()
(this.collapsed() ? 'icon-right-mini e-collapsed-sign' : 'icon-down-mini e-collapsed-sign') : 'icon-none e-collapsed-sign'; ? this.collapsed()
? 'icon-right-mini e-collapsed-sign'
: 'icon-down-mini e-collapsed-sign'
: 'icon-none e-collapsed-sign';
} }
/** /**
@ -278,8 +275,7 @@ class FolderModel extends AbstractModel
let bResult = false; let bResult = false;
const sInboxFolderName = getFolderInboxName(); const sInboxFolderName = getFolderInboxName();
if (json && 'Object/Folder' === json['@Object']) if (json && 'Object/Folder' === json['@Object']) {
{
this.name(json.Name); this.name(json.Name);
this.delimiter = json.Delimiter; this.delimiter = json.Delimiter;
this.fullName = json.FullName; this.fullName = json.FullName;
@ -308,4 +304,4 @@ class FolderModel extends AbstractModel
} }
} }
export {FolderModel, FolderModel as default}; export { FolderModel, FolderModel as default };

View file

@ -1,16 +1,13 @@
import ko from 'ko'; import ko from 'ko';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class IdentityModel extends AbstractModel class IdentityModel extends AbstractModel {
{
/** /**
* @param {string} id * @param {string} id
* @param {string} email * @param {string} email
*/ */
constructor(id, email) constructor(id, email) {
{
super('IdentityModel'); super('IdentityModel');
this.id = ko.observable(id || ''); this.id = ko.observable(id || '');
@ -31,12 +28,11 @@ class IdentityModel extends AbstractModel
* @returns {string} * @returns {string}
*/ */
formattedName() { formattedName() {
const const name = this.name(),
name = this.name(),
email = this.email(); email = this.email();
return '' !== name ? name + ' (' + email + ')' : email; return '' !== name ? name + ' (' + email + ')' : email;
} }
} }
export {IdentityModel, IdentityModel as default}; export { IdentityModel, IdentityModel as default };

View file

@ -1,4 +1,3 @@
import _ from '_'; import _ from '_';
import $ from '$'; import $ from '$';
import ko from 'ko'; import ko from 'ko';
@ -6,28 +5,34 @@ import moment from 'moment';
import classnames from 'classnames'; import classnames from 'classnames';
import lozad from 'lozad'; import lozad from 'lozad';
import {MessagePriority, SignedVerifyStatus} from 'Common/Enums'; import { MessagePriority, SignedVerifyStatus } from 'Common/Enums';
import {i18n} from 'Common/Translator'; import { i18n } from 'Common/Translator';
import {DATA_IMAGE_LAZY_PLACEHOLDER_PIC} from 'Common/Consts'; import { DATA_IMAGE_LAZY_PLACEHOLDER_PIC } from 'Common/Consts';
import { import {
pInt, inArray, isArray, isUnd, trim, pInt,
previewMessage, windowResize, friendlySize, isNonEmptyArray inArray,
isArray,
isUnd,
trim,
previewMessage,
windowResize,
friendlySize,
isNonEmptyArray
} from 'Common/Utils'; } from 'Common/Utils';
import {$win} from 'Common/Globals'; import { $win } from 'Common/Globals';
import {messageViewLink, messageDownloadLink} from 'Common/Links'; import { messageViewLink, messageDownloadLink } from 'Common/Links';
import FolderStore from 'Stores/User/Folder'; import FolderStore from 'Stores/User/Folder';
import PgpStore from 'Stores/User/Pgp'; import PgpStore from 'Stores/User/Pgp';
import {emailArrayFromJson, emailArrayToStringClear, emailArrayToString, replyHelper} from 'Helper/Message'; import { emailArrayFromJson, emailArrayToStringClear, emailArrayToString, replyHelper } from 'Helper/Message';
import {AttachmentModel, staticCombinedIconClass} from 'Model/Attachment'; import { AttachmentModel, staticCombinedIconClass } from 'Model/Attachment';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class MessageModel extends AbstractModel class MessageModel extends AbstractModel {
{
constructor() { constructor() {
super('MessageModel'); super('MessageModel');
@ -78,7 +83,9 @@ class MessageModel extends AbstractModel
this.hasAttachments = ko.observable(false); this.hasAttachments = ko.observable(false);
this.attachmentsSpecData = ko.observableArray([]); this.attachmentsSpecData = ko.observableArray([]);
this.attachmentIconClass = ko.computed(() => staticCombinedIconClass(this.hasAttachments() ? this.attachmentsSpecData() : [])); this.attachmentIconClass = ko.computed(() =>
staticCombinedIconClass(this.hasAttachments() ? this.attachmentsSpecData() : [])
);
this.body = null; this.body = null;
@ -194,10 +201,13 @@ class MessageModel extends AbstractModel
* @returns {Array} * @returns {Array}
*/ */
getEmails(properties) { getEmails(properties) {
return _.compact(_.uniq(_.map( return _.compact(
_.reduce(properties, (carry, property) => carry.concat(this[property]), []), _.uniq(
(oItem) => (oItem ? oItem.email : '') _.map(_.reduce(properties, (carry, property) => carry.concat(this[property]), []), (oItem) =>
))); oItem ? oItem.email : ''
)
)
);
} }
/** /**
@ -215,15 +225,20 @@ class MessageModel extends AbstractModel
} }
computeSenderEmail() { computeSenderEmail() {
const const sentFolder = FolderStore.sentFolder(),
sentFolder = FolderStore.sentFolder(),
draftFolder = FolderStore.draftFolder(); draftFolder = FolderStore.draftFolder();
this.senderEmailsString(this.folderFullNameRaw === sentFolder || this.folderFullNameRaw === draftFolder ? this.senderEmailsString(
this.toEmailsString() : this.fromEmailString()); this.folderFullNameRaw === sentFolder || this.folderFullNameRaw === draftFolder
? this.toEmailsString()
: this.fromEmailString()
);
this.senderClearEmailsString(this.folderFullNameRaw === sentFolder || this.folderFullNameRaw === draftFolder ? this.senderClearEmailsString(
this.toClearEmailsString() : this.fromClearEmailString()); this.folderFullNameRaw === sentFolder || this.folderFullNameRaw === draftFolder
? this.toClearEmailsString()
: this.fromClearEmailString()
);
} }
/** /**
@ -231,14 +246,14 @@ class MessageModel extends AbstractModel
* @returns {boolean} * @returns {boolean}
*/ */
initByJson(json) { initByJson(json) {
let let result = false,
result = false,
priority = MessagePriority.Normal; priority = MessagePriority.Normal;
if (json && 'Object/Message' === json['@Object']) if (json && 'Object/Message' === json['@Object']) {
{
priority = pInt(json.Priority); priority = pInt(json.Priority);
this.priority(-1 < inArray(priority, [MessagePriority.High, MessagePriority.Low]) ? priority : MessagePriority.Normal); this.priority(
-1 < inArray(priority, [MessagePriority.High, MessagePriority.Low]) ? priority : MessagePriority.Normal
);
this.folderFullNameRaw = json.Folder; this.folderFullNameRaw = json.Folder;
this.uid = json.Uid; this.uid = json.Uid;
@ -258,13 +273,10 @@ class MessageModel extends AbstractModel
this.unsubsribeLinks = isNonEmptyArray(json.UnsubsribeLinks) ? json.UnsubsribeLinks : []; this.unsubsribeLinks = isNonEmptyArray(json.UnsubsribeLinks) ? json.UnsubsribeLinks : [];
this.subject(json.Subject); this.subject(json.Subject);
if (isArray(json.SubjectParts)) if (isArray(json.SubjectParts)) {
{
this.subjectPrefix(json.SubjectParts[0]); this.subjectPrefix(json.SubjectParts[0]);
this.subjectSuffix(json.SubjectParts[1]); this.subjectSuffix(json.SubjectParts[1]);
} } else {
else
{
this.subjectPrefix(''); this.subjectPrefix('');
this.subjectSuffix(this.subject()); this.subjectSuffix(this.subject());
} }
@ -294,15 +306,14 @@ class MessageModel extends AbstractModel
* @returns {boolean} * @returns {boolean}
*/ */
initUpdateByMessageJson(json) { initUpdateByMessageJson(json) {
let let result = false,
result = false,
priority = MessagePriority.Normal; priority = MessagePriority.Normal;
if (json && 'Object/Message' === json['@Object']) if (json && 'Object/Message' === json['@Object']) {
{
priority = pInt(json.Priority); priority = pInt(json.Priority);
this.priority(-1 < inArray(priority, [MessagePriority.High, MessagePriority.Low]) ? this.priority(
priority : MessagePriority.Normal); -1 < inArray(priority, [MessagePriority.High, MessagePriority.Low]) ? priority : MessagePriority.Normal
);
this.aDraftInfo = json.DraftInfo; this.aDraftInfo = json.DraftInfo;
@ -312,8 +323,7 @@ class MessageModel extends AbstractModel
this.proxy = !!json.ExternalProxy; this.proxy = !!json.ExternalProxy;
if (PgpStore.capaOpenPGP()) if (PgpStore.capaOpenPGP()) {
{
this.isPgpSigned(!!json.PgpSigned); this.isPgpSigned(!!json.PgpSigned);
this.isPgpEncrypted(!!json.PgpEncrypted); this.isPgpEncrypted(!!json.PgpEncrypted);
} }
@ -339,22 +349,20 @@ class MessageModel extends AbstractModel
* @returns {Array} * @returns {Array}
*/ */
initAttachmentsFromJson(json) { initAttachmentsFromJson(json) {
let let index = 0,
index = 0,
len = 0, len = 0,
attachment = null; attachment = null;
const result = []; const result = [];
if (json && 'Collection/AttachmentCollection' === json['@Object'] && isNonEmptyArray(json['@Collection'])) if (json && 'Collection/AttachmentCollection' === json['@Object'] && isNonEmptyArray(json['@Collection'])) {
{ for (index = 0, len = json['@Collection'].length; index < len; index++) {
for (index = 0, len = json['@Collection'].length; index < len; index++)
{
attachment = AttachmentModel.newInstanceFromJson(json['@Collection'][index]); attachment = AttachmentModel.newInstanceFromJson(json['@Collection'][index]);
if (attachment) if (attachment) {
{ if (
if ('' !== attachment.cidWithOutTags && 0 < this.foundedCIDs.length && '' !== attachment.cidWithOutTags &&
0 <= inArray(attachment.cidWithOutTags, this.foundedCIDs)) 0 < this.foundedCIDs.length &&
{ 0 <= inArray(attachment.cidWithOutTags, this.foundedCIDs)
) {
attachment.isLinked = true; attachment.isLinked = true;
} }
@ -377,7 +385,7 @@ class MessageModel extends AbstractModel
* @returns {string} * @returns {string}
*/ */
getFirstUnsubsribeLink() { getFirstUnsubsribeLink() {
return this.unsubsribeLinks && 0 < this.unsubsribeLinks.length ? (this.unsubsribeLinks[0] || '') : ''; return this.unsubsribeLinks && 0 < this.unsubsribeLinks.length ? this.unsubsribeLinks[0] || '' : '';
} }
/** /**
@ -386,8 +394,7 @@ class MessageModel extends AbstractModel
*/ */
initFlagsByJson(json) { initFlagsByJson(json) {
let result = false; let result = false;
if (json && 'Object/Message' === json['@Object']) if (json && 'Object/Message' === json['@Object']) {
{
this.unseen(!json.IsSeen); this.unseen(!json.IsSeen);
this.flagged(!!json.IsFlagged); this.flagged(!!json.IsFlagged);
this.answered(!!json.IsAnswered); this.answered(!!json.IsAnswered);
@ -415,8 +422,7 @@ class MessageModel extends AbstractModel
*/ */
fromDkimData() { fromDkimData() {
let result = ['none', '']; let result = ['none', ''];
if (isNonEmptyArray(this.from) && 1 === this.from.length && this.from[0] && this.from[0].dkimStatus) if (isNonEmptyArray(this.from) && 1 === this.from.length && this.from[0] && this.from[0].dkimStatus) {
{
result = [this.from[0].dkimStatus, this.from[0].dkimValue || '']; result = [this.from[0].dkimStatus, this.from[0].dkimValue || ''];
} }
@ -498,8 +504,7 @@ class MessageModel extends AbstractModel
let result = null; let result = null;
const attachments = this.attachments(); const attachments = this.attachments();
if (isNonEmptyArray(attachments)) if (isNonEmptyArray(attachments)) {
{
cid = cid.replace(/^<+/, '').replace(/>+$/, ''); cid = cid.replace(/^<+/, '').replace(/>+$/, '');
result = _.find(attachments, (item) => cid === item.cidWithOutTags); result = _.find(attachments, (item) => cid === item.cidWithOutTags);
} }
@ -515,8 +520,7 @@ class MessageModel extends AbstractModel
let result = null; let result = null;
const attachments = this.attachments(); const attachments = this.attachments();
if (isNonEmptyArray(attachments)) if (isNonEmptyArray(attachments)) {
{
result = _.find(attachments, (item) => contentLocation === item.contentLocation); result = _.find(attachments, (item) => contentLocation === item.contentLocation);
} }
@ -571,18 +575,15 @@ class MessageModel extends AbstractModel
* @returns {Array} * @returns {Array}
*/ */
replyEmails(excludeEmails, last = false) { replyEmails(excludeEmails, last = false) {
const const result = [],
result = [],
unic = isUnd(excludeEmails) ? {} : excludeEmails; unic = isUnd(excludeEmails) ? {} : excludeEmails;
replyHelper(this.replyTo, unic, result); replyHelper(this.replyTo, unic, result);
if (0 === result.length) if (0 === result.length) {
{
replyHelper(this.from, unic, result); replyHelper(this.from, unic, result);
} }
if (0 === result.length && !last) if (0 === result.length && !last) {
{
return this.replyEmails({}, true); return this.replyEmails({}, true);
} }
@ -596,22 +597,19 @@ class MessageModel extends AbstractModel
*/ */
replyAllEmails(excludeEmails, last = false) { replyAllEmails(excludeEmails, last = false) {
let data = []; let data = [];
const const toResult = [],
toResult = [],
ccResult = [], ccResult = [],
unic = isUnd(excludeEmails) ? {} : excludeEmails; unic = isUnd(excludeEmails) ? {} : excludeEmails;
replyHelper(this.replyTo, unic, toResult); replyHelper(this.replyTo, unic, toResult);
if (0 === toResult.length) if (0 === toResult.length) {
{
replyHelper(this.from, unic, toResult); replyHelper(this.from, unic, toResult);
} }
replyHelper(this.to, unic, toResult); replyHelper(this.to, unic, toResult);
replyHelper(this.cc, unic, ccResult); replyHelper(this.cc, unic, ccResult);
if (0 === toResult.length && !last) if (0 === toResult.length && !last) {
{
data = this.replyAllEmails({}, true); data = this.replyAllEmails({}, true);
return [data[0], ccResult]; return [data[0], ccResult];
} }
@ -640,22 +638,26 @@ class MessageModel extends AbstractModel
viewPopupMessage(print = false) { viewPopupMessage(print = false) {
this.showLazyExternalImagesInBody(); this.showLazyExternalImagesInBody();
const const timeStampInUTC = this.dateTimeStampInUTC() || 0,
timeStampInUTC = this.dateTimeStampInUTC() || 0,
ccLine = this.ccToLine(false), ccLine = this.ccToLine(false),
m = 0 < timeStampInUTC ? moment.unix(timeStampInUTC) : null; m = 0 < timeStampInUTC ? moment.unix(timeStampInUTC) : null;
previewMessage({ previewMessage(
title: this.subject(), {
subject: this.subject(), title: this.subject(),
date: m ? m.format('LLL') : '', subject: this.subject(),
fromCreds: this.fromToLine(false), date: m ? m.format('LLL') : '',
toLabel: i18n('MESSAGE/LABEL_TO'), fromCreds: this.fromToLine(false),
toCreds: this.toToLine(false), toLabel: i18n('MESSAGE/LABEL_TO'),
ccClass: ccLine ? '' : 'rl-preview-hide', toCreds: this.toToLine(false),
ccLabel: i18n('MESSAGE/LABEL_CC'), ccClass: ccLine ? '' : 'rl-preview-hide',
ccCreds: ccLine ccLabel: i18n('MESSAGE/LABEL_CC'),
}, this.body, this.isHtml(), print); ccCreds: ccLine
},
this.body,
this.isHtml(),
print
);
} }
printMessage() { printMessage() {
@ -674,8 +676,7 @@ class MessageModel extends AbstractModel
* @returns {MessageModel} * @returns {MessageModel}
*/ */
populateByMessageListItem(message) { populateByMessageListItem(message) {
if (message) if (message) {
{
this.folderFullNameRaw = message.folderFullNameRaw; this.folderFullNameRaw = message.folderFullNameRaw;
this.uid = message.uid; this.uid = message.uid;
this.hash = message.hash; this.hash = message.hash;
@ -686,8 +687,7 @@ class MessageModel extends AbstractModel
this.subjectPrefix(this.subjectPrefix()); this.subjectPrefix(this.subjectPrefix());
this.subjectSuffix(this.subjectSuffix()); this.subjectSuffix(this.subjectSuffix());
if (message) if (message) {
{
this.size(message.size()); this.size(message.size());
this.dateTimeStampInUTC(message.dateTimeStampInUTC()); this.dateTimeStampInUTC(message.dateTimeStampInUTC());
this.priority(message.priority()); this.priority(message.priority());
@ -731,8 +731,7 @@ class MessageModel extends AbstractModel
this.sInReplyTo = ''; this.sInReplyTo = '';
this.sReferences = ''; this.sReferences = '';
if (message) if (message) {
{
this.threads(message.threads()); this.threads(message.threads());
} }
@ -742,11 +741,12 @@ class MessageModel extends AbstractModel
} }
showLazyExternalImagesInBody() { showLazyExternalImagesInBody() {
if (this.body) if (this.body) {
{
$('.lazy.lazy-inited[data-original]', this.body).each(function() { $('.lazy.lazy-inited[data-original]', this.body).each(function() {
$(this).attr('src', $(this).attr('data-original')) // eslint-disable-line no-invalid-this $(this)
.removeAttr('data-original').removeAttr('data-loaded'); .attr('src', $(this).attr('data-original')) // eslint-disable-line no-invalid-this
.removeAttr('data-original')
.removeAttr('data-loaded');
}); });
} }
} }
@ -762,32 +762,27 @@ class MessageModel extends AbstractModel
.attr('src', element.dataset.original) .attr('src', element.dataset.original)
.removeAttr('data-loaded') .removeAttr('data-loaded')
.removeAttr('data-original') .removeAttr('data-original')
.css({opacity: 0.3}) .css({ opacity: 0.3 })
.animate({opacity: 1}, 500); .animate({ opacity: 1 }, 500);
} }
}).observe(); }).observe();
} }
showExternalImages(lazy = false) { showExternalImages(lazy = false) {
if (this.body && this.body.data('rl-has-images')) if (this.body && this.body.data('rl-has-images')) {
{
this.hasImages(false); this.hasImages(false);
this.body.data('rl-has-images', false); this.body.data('rl-has-images', false);
let attr = this.proxy ? 'data-x-additional-src' : 'data-x-src'; let attr = this.proxy ? 'data-x-additional-src' : 'data-x-src';
$('[' + attr + ']', this.body).each(function() { $('[' + attr + ']', this.body).each(function() {
const $this = $(this); // eslint-disable-line no-invalid-this const $this = $(this); // eslint-disable-line no-invalid-this
if (lazy && $this.is('img')) if (lazy && $this.is('img')) {
{
$this $this
.addClass('lazy') .addClass('lazy')
.attr('data-original', $this.attr(attr)) .attr('data-original', $this.attr(attr))
.removeAttr('data-loaded'); .removeAttr('data-loaded');
} } else {
else $this.attr('src', $this.attr(attr)).removeAttr('data-loaded');
{
$this.attr('src', $this.attr(attr))
.removeAttr('data-loaded');
} }
}); });
@ -795,12 +790,11 @@ class MessageModel extends AbstractModel
$('[' + attr + ']', this.body).each(function() { $('[' + attr + ']', this.body).each(function() {
const $this = $(this); // eslint-disable-line no-invalid-this const $this = $(this); // eslint-disable-line no-invalid-this
let style = trim($this.attr('style')); let style = trim($this.attr('style'));
style = '' === style ? '' : (';' === style.substr(-1) ? style + ' ' : style + '; '); style = '' === style ? '' : ';' === style.substr(-1) ? style + ' ' : style + '; ';
$this.attr('style', style + $this.attr(attr)); $this.attr('style', style + $this.attr(attr));
}); });
if (lazy) if (lazy) {
{
this.lozad(); this.lozad();
$win.resize(); $win.resize();
} }
@ -810,27 +804,19 @@ class MessageModel extends AbstractModel
} }
showInternalImages(lazy = false) { showInternalImages(lazy = false) {
if (this.body && !this.body.data('rl-init-internal-images')) if (this.body && !this.body.data('rl-init-internal-images')) {
{
this.body.data('rl-init-internal-images', true); this.body.data('rl-init-internal-images', true);
const self = this; const self = this;
$('[data-x-src-cid]', this.body).each(function() { $('[data-x-src-cid]', this.body).each(function() {
const const $this = $(this), // eslint-disable-line no-invalid-this
$this = $(this), // eslint-disable-line no-invalid-this
attachment = self.findAttachmentByCid($this.attr('data-x-src-cid')); attachment = self.findAttachmentByCid($this.attr('data-x-src-cid'));
if (attachment && attachment.download) if (attachment && attachment.download) {
{ if (lazy && $this.is('img')) {
if (lazy && $this.is('img')) $this.addClass('lazy').attr('data-original', attachment.linkPreview());
{ } else {
$this
.addClass('lazy')
.attr('data-original', attachment.linkPreview());
}
else
{
$this.attr('src', attachment.linkPreview()); $this.attr('src', attachment.linkPreview());
} }
} }
@ -839,49 +825,37 @@ class MessageModel extends AbstractModel
$('[data-x-src-location]', this.body).each(function() { $('[data-x-src-location]', this.body).each(function() {
const $this = $(this); // eslint-disable-line no-invalid-this const $this = $(this); // eslint-disable-line no-invalid-this
let attachment = self.findAttachmentByContentLocation($this.attr('data-x-src-location')); let attachment = self.findAttachmentByContentLocation($this.attr('data-x-src-location'));
if (!attachment) if (!attachment) {
{
attachment = self.findAttachmentByCid($this.attr('data-x-src-location')); attachment = self.findAttachmentByCid($this.attr('data-x-src-location'));
} }
if (attachment && attachment.download) if (attachment && attachment.download) {
{ if (lazy && $this.is('img')) {
if (lazy && $this.is('img')) $this.addClass('lazy').attr('data-original', attachment.linkPreview());
{ } else {
$this
.addClass('lazy')
.attr('data-original', attachment.linkPreview());
}
else
{
$this.attr('src', attachment.linkPreview()); $this.attr('src', attachment.linkPreview());
} }
} }
}); });
$('[data-x-style-cid]', this.body).each(function() { $('[data-x-style-cid]', this.body).each(function() {
let let style = '',
style = '',
name = ''; name = '';
const const $this = $(this), // eslint-disable-line no-invalid-this
$this = $(this), // eslint-disable-line no-invalid-this
attachment = self.findAttachmentByCid($this.attr('data-x-style-cid')); attachment = self.findAttachmentByCid($this.attr('data-x-style-cid'));
if (attachment && attachment.linkPreview) if (attachment && attachment.linkPreview) {
{
name = $this.attr('data-x-style-cid-name'); name = $this.attr('data-x-style-cid-name');
if ('' !== name) if ('' !== name) {
{
style = trim($this.attr('style')); style = trim($this.attr('style'));
style = '' === style ? '' : (';' === style.substr(-1) ? style + ' ' : style + '; '); style = '' === style ? '' : ';' === style.substr(-1) ? style + ' ' : style + '; ';
$this.attr('style', style + name + ': url(\'' + attachment.linkPreview() + '\')'); $this.attr('style', style + name + ": url('" + attachment.linkPreview() + "')");
} }
} }
}); });
if (lazy) if (lazy) {
{
// $('.RL-MailMessageView .messageView .messageItem .content')[0] // $('.RL-MailMessageView .messageView .messageItem .content')[0]
_.delay(() => this.lozad(), 300); _.delay(() => this.lozad(), 300);
} }
@ -891,24 +865,21 @@ class MessageModel extends AbstractModel
} }
storeDataInDom() { storeDataInDom() {
if (this.body) if (this.body) {
{
this.body.data('rl-is-html', !!this.isHtml()); this.body.data('rl-is-html', !!this.isHtml());
this.body.data('rl-has-images', !!this.hasImages()); this.body.data('rl-has-images', !!this.hasImages());
} }
} }
fetchDataFromDom() { fetchDataFromDom() {
if (this.body) if (this.body) {
{
this.isHtml(!!this.body.data('rl-is-html')); this.isHtml(!!this.body.data('rl-is-html'));
this.hasImages(!!this.body.data('rl-has-images')); this.hasImages(!!this.body.data('rl-has-images'));
} }
} }
replacePlaneTextBody(plain) { replacePlaneTextBody(plain) {
if (this.body) if (this.body) {
{
this.body.html(plain).addClass('b-text-part plain'); this.body.html(plain).addClass('b-text-part plain');
} }
} }
@ -917,8 +888,16 @@ class MessageModel extends AbstractModel
* @returns {string} * @returns {string}
*/ */
flagHash() { flagHash() {
return [this.deleted(), this.deletedMark(), this.unseen(), this.flagged(), this.answered(), this.forwarded(), this.isReadReceipt()].join(','); return [
this.deleted(),
this.deletedMark(),
this.unseen(),
this.flagged(),
this.answered(),
this.forwarded(),
this.isReadReceipt()
].join(',');
} }
} }
export {MessageModel, MessageModel as default}; export { MessageModel, MessageModel as default };

View file

@ -1,14 +1,12 @@
import ko from 'ko'; import ko from 'ko';
import {isNonEmptyArray, log} from 'Common/Utils'; import { isNonEmptyArray, log } from 'Common/Utils';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
import PgpStore from 'Stores/User/Pgp'; import PgpStore from 'Stores/User/Pgp';
class OpenPgpKeyModel extends AbstractModel class OpenPgpKeyModel extends AbstractModel {
{
/** /**
* @param {string} index * @param {string} index
* @param {string} guID * @param {string} guID
@ -20,8 +18,7 @@ class OpenPgpKeyModel extends AbstractModel
* @param {string} armor * @param {string} armor
* @param {string} userID * @param {string} userID
*/ */
constructor(index, guID, ID, IDs, userIDs, emails, isPrivate, armor, userID) constructor(index, guID, ID, IDs, userIDs, emails, isPrivate, armor, userID) {
{
super('OpenPgpKeyModel'); super('OpenPgpKeyModel');
this.index = index; this.index = index;
@ -42,16 +39,12 @@ class OpenPgpKeyModel extends AbstractModel
getNativeKey() { getNativeKey() {
let key = null; let key = null;
try try {
{
key = PgpStore.openpgp.key.readArmored(this.armor); key = PgpStore.openpgp.key.readArmored(this.armor);
if (key && !key.err && key.keys && key.keys[0]) if (key && !key.err && key.keys && key.keys[0]) {
{
return key; return key;
} }
} } catch (e) {
catch (e)
{
log(e); log(e);
} }
@ -64,11 +57,9 @@ class OpenPgpKeyModel extends AbstractModel
} }
select(pattern, property) { select(pattern, property) {
if (this[property]) if (this[property]) {
{
const index = this[property].indexOf(pattern); const index = this[property].indexOf(pattern);
if (-1 !== index) if (-1 !== index) {
{
this.user = this.users[index]; this.user = this.users[index];
this.email = this.emails[index]; this.email = this.emails[index];
} }
@ -84,4 +75,4 @@ class OpenPgpKeyModel extends AbstractModel
} }
} }
export {OpenPgpKeyModel, OpenPgpKeyModel as default}; export { OpenPgpKeyModel, OpenPgpKeyModel as default };

View file

@ -1,19 +1,16 @@
import ko from 'ko'; import ko from 'ko';
import {pString} from 'Common/Utils'; import { pString } from 'Common/Utils';
import {AbstractModel} from 'Knoin/AbstractModel'; import { AbstractModel } from 'Knoin/AbstractModel';
class TemplateModel extends AbstractModel class TemplateModel extends AbstractModel {
{
/** /**
* @param {string} id * @param {string} id
* @param {string} name * @param {string} name
* @param {string} body * @param {string} body
*/ */
constructor(id, name, body) constructor(id, name, body) {
{
super('TemplateModel'); super('TemplateModel');
this.id = id; this.id = id;
@ -29,8 +26,7 @@ class TemplateModel extends AbstractModel
*/ */
parse(json) { parse(json) {
let result = false; let result = false;
if (json && 'Object/Template' === json['@Object']) if (json && 'Object/Template' === json['@Object']) {
{
this.id = pString(json.ID); this.id = pString(json.ID);
this.name = pString(json.Name); this.name = pString(json.Name);
this.body = pString(json.Body); this.body = pString(json.Body);
@ -43,4 +39,4 @@ class TemplateModel extends AbstractModel
} }
} }
export {TemplateModel, TemplateModel as default}; export { TemplateModel, TemplateModel as default };

View file

@ -1,19 +1,17 @@
import window from 'window'; import window from 'window';
import $ from '$'; import $ from '$';
import {ajax} from 'Common/Links'; import { ajax } from 'Common/Links';
import {microtime, isUnd, isNormal, pString, pInt, inArray} from 'Common/Utils'; import { microtime, isUnd, isNormal, pString, pInt, inArray } from 'Common/Utils';
import {DEFAULT_AJAX_TIMEOUT, TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT} from 'Common/Consts'; import { DEFAULT_AJAX_TIMEOUT, TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT } from 'Common/Consts';
import {StorageResultType, Notification} from 'Common/Enums'; import { StorageResultType, Notification } from 'Common/Enums';
import {data as GlobalsData} from 'Common/Globals'; import { data as GlobalsData } from 'Common/Globals';
import * as Plugins from 'Common/Plugins'; import * as Plugins from 'Common/Plugins';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
import {AbstractBasicPromises} from 'Promises/AbstractBasic'; import { AbstractBasicPromises } from 'Promises/AbstractBasic';
class AbstractAjaxPromises extends AbstractBasicPromises class AbstractAjaxPromises extends AbstractBasicPromises {
{
oRequests = {}; oRequests = {};
constructor() { constructor() {
@ -27,10 +25,8 @@ class AbstractAjaxPromises extends AbstractBasicPromises
} }
abort(sAction, bClearOnly) { abort(sAction, bClearOnly) {
if (this.oRequests[sAction]) if (this.oRequests[sAction]) {
{ if (!bClearOnly && this.oRequests[sAction].abort) {
if (!bClearOnly && this.oRequests[sAction].abort)
{
this.oRequests[sAction].__aborted__ = true; this.oRequests[sAction].__aborted__ = true;
this.oRequests[sAction].abort(); this.oRequests[sAction].abort();
} }
@ -43,16 +39,13 @@ class AbstractAjaxPromises extends AbstractBasicPromises
} }
ajaxRequest(action, isPost, timeOut, params, additionalGetString, fTrigger) { ajaxRequest(action, isPost, timeOut, params, additionalGetString, fTrigger) {
return new window.Promise((resolve, reject) => { return new window.Promise((resolve, reject) => {
const start = microtime(); const start = microtime();
timeOut = isNormal(timeOut) ? timeOut : DEFAULT_AJAX_TIMEOUT; timeOut = isNormal(timeOut) ? timeOut : DEFAULT_AJAX_TIMEOUT;
additionalGetString = isUnd(additionalGetString) ? '' : pString(additionalGetString); additionalGetString = isUnd(additionalGetString) ? '' : pString(additionalGetString);
if (isPost) if (isPost) {
{
params.XToken = Settings.appSettingsGet('token'); params.XToken = Settings.appSettingsGet('token');
} }
@ -65,24 +58,20 @@ class AbstractAjaxPromises extends AbstractBasicPromises
url: ajax(additionalGetString), url: ajax(additionalGetString),
async: true, async: true,
dataType: 'json', dataType: 'json',
data: isPost ? (params || {}) : {}, data: isPost ? params || {} : {},
timeout: timeOut, timeout: timeOut,
global: true global: true
}).always((data, textStatus) => { }).always((data, textStatus) => {
let isCached = false,
let
isCached = false,
errorData = null; errorData = null;
if (data && data.Time) if (data && data.Time) {
{
isCached = pInt(data.Time) > microtime() - start; isCached = pInt(data.Time) > microtime() - start;
} }
// backward capability // backward capability
let type = ''; let type = '';
switch (true) switch (true) {
{
case 'success' === textStatus && data && data.Result && action === data.Action: case 'success' === textStatus && data && data.Result && action === data.Action:
type = StorageResultType.Success; type = StorageResultType.Success;
break; break;
@ -95,97 +84,84 @@ class AbstractAjaxPromises extends AbstractBasicPromises
} }
Plugins.runHook('ajax-default-response', [ Plugins.runHook('ajax-default-response', [
action, StorageResultType.Success === type ? data : null, type, isCached, params action,
StorageResultType.Success === type ? data : null,
type,
isCached,
params
]); ]);
if ('success' === textStatus) if ('success' === textStatus) {
{ if (data && data.Result && action === data.Action) {
if (data && data.Result && action === data.Action)
{
data.__cached__ = isCached; data.__cached__ = isCached;
resolve(data); resolve(data);
} } else if (data && data.Action) {
else if (data && data.Action)
{
errorData = data; errorData = data;
reject(data.ErrorCode ? data.ErrorCode : Notification.AjaxFalse); reject(data.ErrorCode ? data.ErrorCode : Notification.AjaxFalse);
} } else {
else
{
errorData = data; errorData = data;
reject(Notification.AjaxParse); reject(Notification.AjaxParse);
} }
} } else if ('timeout' === textStatus) {
else if ('timeout' === textStatus)
{
errorData = data; errorData = data;
reject(Notification.AjaxTimeout); reject(Notification.AjaxTimeout);
} } else if ('abort' === textStatus) {
else if ('abort' === textStatus) if (!data || !data.__aborted__) {
{
if (!data || !data.__aborted__)
{
reject(Notification.AjaxAbort); reject(Notification.AjaxAbort);
} }
} } else {
else
{
errorData = data; errorData = data;
reject(Notification.AjaxParse); reject(Notification.AjaxParse);
} }
if (this.oRequests[action]) if (this.oRequests[action]) {
{
this.oRequests[action] = null; this.oRequests[action] = null;
delete this.oRequests[action]; delete this.oRequests[action];
} }
this.setTrigger(fTrigger, false); this.setTrigger(fTrigger, false);
if (errorData) if (errorData) {
{ if (
if (-1 < inArray(errorData.ErrorCode, [ -1 <
Notification.AuthError, Notification.AccessError, inArray(errorData.ErrorCode, [
Notification.ConnectionError, Notification.DomainNotAllowed, Notification.AccountNotAllowed, Notification.AuthError,
Notification.MailServerError, Notification.UnknownNotification, Notification.UnknownError Notification.AccessError,
])) Notification.ConnectionError,
{ Notification.DomainNotAllowed,
Notification.AccountNotAllowed,
Notification.MailServerError,
Notification.UnknownNotification,
Notification.UnknownError
])
) {
GlobalsData.iAjaxErrorCount += 1; GlobalsData.iAjaxErrorCount += 1;
} }
if (Notification.InvalidToken === errorData.ErrorCode) if (Notification.InvalidToken === errorData.ErrorCode) {
{
GlobalsData.iTokenErrorCount += 1; GlobalsData.iTokenErrorCount += 1;
} }
if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount) if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount) {
{ if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload) {
if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload)
{
GlobalsData.__APP__.loginAndLogoutReload(false, true); GlobalsData.__APP__.loginAndLogoutReload(false, true);
} }
} }
if (errorData.ClearAuth || errorData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount) if (errorData.ClearAuth || errorData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount) {
{ if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken) {
if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken)
{
GlobalsData.__APP__.clearClientSideToken(); GlobalsData.__APP__.clearClientSideToken();
} }
if (GlobalsData.__APP__ && !errorData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload) if (GlobalsData.__APP__ && !errorData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload) {
{
GlobalsData.__APP__.loginAndLogoutReload(false, true); GlobalsData.__APP__.loginAndLogoutReload(false, true);
} }
} }
} }
}); });
if (oH) if (oH) {
{ if (this.oRequests[action]) {
if (this.oRequests[action])
{
this.oRequests[action] = null; this.oRequests[action] = null;
delete this.oRequests[action]; delete this.oRequests[action];
} }
@ -196,7 +172,6 @@ class AbstractAjaxPromises extends AbstractBasicPromises
} }
getRequest(sAction, fTrigger, sAdditionalGetString, iTimeOut) { getRequest(sAction, fTrigger, sAdditionalGetString, iTimeOut) {
sAdditionalGetString = isUnd(sAdditionalGetString) ? '' : pString(sAdditionalGetString); sAdditionalGetString = isUnd(sAdditionalGetString) ? '' : pString(sAdditionalGetString);
sAdditionalGetString = sAction + '/' + sAdditionalGetString; sAdditionalGetString = sAction + '/' + sAdditionalGetString;
@ -204,7 +179,6 @@ class AbstractAjaxPromises extends AbstractBasicPromises
} }
postRequest(action, fTrigger, params, timeOut) { postRequest(action, fTrigger, params, timeOut) {
params = params || {}; params = params || {};
params.Action = action; params.Action = action;
@ -212,4 +186,4 @@ class AbstractAjaxPromises extends AbstractBasicPromises
} }
} }
export {AbstractAjaxPromises, AbstractAjaxPromises as default}; export { AbstractAjaxPromises, AbstractAjaxPromises as default };

View file

@ -1,9 +1,7 @@
import window from 'window'; import window from 'window';
import {isArray} from 'Common/Utils'; import { isArray } from 'Common/Utils';
export class AbstractBasicPromises export class AbstractBasicPromises {
{
oPromisesStack = {}; oPromisesStack = {};
func(fFunc) { func(fFunc) {
@ -20,12 +18,10 @@ export class AbstractBasicPromises
} }
setTrigger(trigger, value) { setTrigger(trigger, value) {
if (trigger) if (trigger) {
{
value = !!value; value = !!value;
(isArray(trigger) ? trigger : [trigger]).forEach((fTrigger) => { (isArray(trigger) ? trigger : [trigger]).forEach((fTrigger) => {
if (fTrigger) if (fTrigger) {
{
fTrigger(value); fTrigger(value);
} }
}); });

View file

@ -1,11 +1,9 @@
import window from 'window'; import window from 'window';
import PromisesPopulator from 'Promises/User/Populator'; import PromisesPopulator from 'Promises/User/Populator';
import {AbstractAjaxPromises} from 'Promises/AbstractAjax'; import { AbstractAjaxPromises } from 'Promises/AbstractAjax';
class UserAjaxUserPromises extends AbstractAjaxPromises class UserAjaxUserPromises extends AbstractAjaxPromises {
{
constructor() { constructor() {
super(); super();
@ -13,11 +11,13 @@ class UserAjaxUserPromises extends AbstractAjaxPromises
} }
foldersReload(fTrigger) { foldersReload(fTrigger) {
return this.abort('Folders').postRequest('Folders', fTrigger).then((data) => { return this.abort('Folders')
PromisesPopulator.foldersList(data.Result); .postRequest('Folders', fTrigger)
PromisesPopulator.foldersAdditionalParameters(data.Result); .then((data) => {
return true; PromisesPopulator.foldersList(data.Result);
}); PromisesPopulator.foldersAdditionalParameters(data.Result);
return true;
});
} }
foldersReloadWithTimeout(fTrigger) { foldersReloadWithTimeout(fTrigger) {

View file

@ -1,9 +1,8 @@
import _ from '_'; import _ from '_';
import {UNUSED_OPTION_VALUE} from 'Common/Consts'; import { UNUSED_OPTION_VALUE } from 'Common/Consts';
import {isArray, isNormal, pInt, isUnd, noop} from 'Common/Utils'; import { isArray, isNormal, pInt, isUnd, noop } from 'Common/Utils';
import {ClientSideKeyName, ServerFolderType} from 'Common/Enums'; import { ClientSideKeyName, ServerFolderType } from 'Common/Enums';
import * as Cache from 'Common/Cache'; import * as Cache from 'Common/Cache';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
@ -14,11 +13,10 @@ import FolderStore from 'Stores/User/Folder';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
import {FolderModel} from 'Model/Folder'; import { FolderModel } from 'Model/Folder';
import {AbstractBasicPromises} from 'Promises/AbstractBasic'; import { AbstractBasicPromises } from 'Promises/AbstractBasic';
class PromisesUserPopulator extends AbstractBasicPromises class PromisesUserPopulator extends AbstractBasicPromises {
{
/** /**
* @param {string} sFullNameHash * @param {string} sFullNameHash
* @param {Array?} expandedFolders * @param {Array?} expandedFolders
@ -33,8 +31,11 @@ class PromisesUserPopulator extends AbstractBasicPromises
* @returns {string} * @returns {string}
*/ */
normalizeFolder(sFolderFullNameRaw) { normalizeFolder(sFolderFullNameRaw) {
return ('' === sFolderFullNameRaw || UNUSED_OPTION_VALUE === sFolderFullNameRaw || return '' === sFolderFullNameRaw ||
null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : ''; UNUSED_OPTION_VALUE === sFolderFullNameRaw ||
null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)
? sFolderFullNameRaw
: '';
} }
/** /**
@ -44,61 +45,52 @@ class PromisesUserPopulator extends AbstractBasicPromises
* @returns {Array} * @returns {Array}
*/ */
folderResponseParseRec(sNamespace, aFolders, expandedFolders) { folderResponseParseRec(sNamespace, aFolders, expandedFolders) {
const bDisplaySpecSetting = FolderStore.displaySpecSetting(),
const
bDisplaySpecSetting = FolderStore.displaySpecSetting(),
aList = []; aList = [];
_.each(aFolders, (oFolder) => { _.each(aFolders, (oFolder) => {
if (oFolder) if (oFolder) {
{
let oCacheFolder = Cache.getFolderFromCacheList(oFolder.FullNameRaw); let oCacheFolder = Cache.getFolderFromCacheList(oFolder.FullNameRaw);
if (!oCacheFolder) if (!oCacheFolder) {
{
oCacheFolder = FolderModel.newInstanceFromJson(oFolder); oCacheFolder = FolderModel.newInstanceFromJson(oFolder);
if (oCacheFolder) if (oCacheFolder) {
{
Cache.setFolderToCacheList(oFolder.FullNameRaw, oCacheFolder); Cache.setFolderToCacheList(oFolder.FullNameRaw, oCacheFolder);
Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, oFolder.FullNameRaw, oCacheFolder); Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, oFolder.FullNameRaw, oCacheFolder);
} }
} }
if (oCacheFolder) if (oCacheFolder) {
{ if (bDisplaySpecSetting) {
if (bDisplaySpecSetting)
{
oCacheFolder.checkable(!!oFolder.Checkable); oCacheFolder.checkable(!!oFolder.Checkable);
} } else {
else
{
oCacheFolder.checkable(true); oCacheFolder.checkable(true);
} }
oCacheFolder.collapsed(!this.isFolderExpanded(oCacheFolder.fullNameHash, expandedFolders)); oCacheFolder.collapsed(!this.isFolderExpanded(oCacheFolder.fullNameHash, expandedFolders));
if (oFolder.Extended) if (oFolder.Extended) {
{ if (oFolder.Extended.Hash) {
if (oFolder.Extended.Hash)
{
Cache.setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash); Cache.setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash);
} }
if (isNormal(oFolder.Extended.MessageCount)) if (isNormal(oFolder.Extended.MessageCount)) {
{
oCacheFolder.messageCountAll(oFolder.Extended.MessageCount); oCacheFolder.messageCountAll(oFolder.Extended.MessageCount);
} }
if (isNormal(oFolder.Extended.MessageUnseenCount)) if (isNormal(oFolder.Extended.MessageUnseenCount)) {
{
oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount); oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount);
} }
} }
if (oFolder.SubFolders && 'Collection/FolderCollection' === oFolder.SubFolders['@Object'] && if (
oFolder.SubFolders['@Collection'] && isArray(oFolder.SubFolders['@Collection'])) oFolder.SubFolders &&
{ 'Collection/FolderCollection' === oFolder.SubFolders['@Object'] &&
oFolder.SubFolders['@Collection'] &&
isArray(oFolder.SubFolders['@Collection'])
) {
oCacheFolder.subFolders( oCacheFolder.subFolders(
this.folderResponseParseRec(sNamespace, oFolder.SubFolders['@Collection'], expandedFolders)); this.folderResponseParseRec(sNamespace, oFolder.SubFolders['@Collection'], expandedFolders)
);
} }
aList.push(oCacheFolder); aList.push(oCacheFolder);
@ -110,29 +102,39 @@ class PromisesUserPopulator extends AbstractBasicPromises
} }
foldersList(oData) { foldersList(oData) {
if (oData && 'Collection/FolderCollection' === oData['@Object'] && if (
oData['@Collection'] && isArray(oData['@Collection'])) oData &&
{ 'Collection/FolderCollection' === oData['@Object'] &&
const oData['@Collection'] &&
expandedFolders = Local.get(ClientSideKeyName.ExpandedFolders), isArray(oData['@Collection'])
) {
const expandedFolders = Local.get(ClientSideKeyName.ExpandedFolders),
cnt = pInt(oData.CountRec); cnt = pInt(oData.CountRec);
let limit = pInt(Settings.appSettingsGet('folderSpecLimit')); let limit = pInt(Settings.appSettingsGet('folderSpecLimit'));
limit = 100 < limit ? 100 : (10 > limit ? 10 : limit); limit = 100 < limit ? 100 : 10 > limit ? 10 : limit;
FolderStore.displaySpecSetting(0 >= cnt || limit < cnt); FolderStore.displaySpecSetting(0 >= cnt || limit < cnt);
FolderStore.folderList(this.folderResponseParseRec( FolderStore.folderList(
isUnd(oData.Namespace) ? '' : oData.Namespace, oData['@Collection'], expandedFolders)); // @todo optimization required this.folderResponseParseRec(
isUnd(oData.Namespace) ? '' : oData.Namespace,
oData['@Collection'],
expandedFolders
)
); // @todo optimization required
} }
} }
foldersAdditionalParameters(oData) { foldersAdditionalParameters(oData) {
if (oData && oData && 'Collection/FolderCollection' === oData['@Object'] && if (
oData['@Collection'] && isArray(oData['@Collection'])) oData &&
{ oData &&
if (!isUnd(oData.Namespace)) 'Collection/FolderCollection' === oData['@Object'] &&
{ oData['@Collection'] &&
isArray(oData['@Collection'])
) {
if (!isUnd(oData.Namespace)) {
FolderStore.namespace = oData.Namespace; FolderStore.namespace = oData.Namespace;
} }
@ -142,14 +144,17 @@ class PromisesUserPopulator extends AbstractBasicPromises
let update = false; let update = false;
if (oData.SystemFolders && '' === '' + if (
Settings.settingsGet('SentFolder') + oData.SystemFolders &&
Settings.settingsGet('DraftFolder') + '' ===
Settings.settingsGet('SpamFolder') + '' +
Settings.settingsGet('TrashFolder') + Settings.settingsGet('SentFolder') +
Settings.settingsGet('ArchiveFolder') + Settings.settingsGet('DraftFolder') +
Settings.settingsGet('NullFolder')) Settings.settingsGet('SpamFolder') +
{ Settings.settingsGet('TrashFolder') +
Settings.settingsGet('ArchiveFolder') +
Settings.settingsGet('NullFolder')
) {
Settings.settingsSet('SentFolder', oData.SystemFolders[ServerFolderType.SENT] || null); Settings.settingsSet('SentFolder', oData.SystemFolders[ServerFolderType.SENT] || null);
Settings.settingsSet('DraftFolder', oData.SystemFolders[ServerFolderType.DRAFTS] || null); Settings.settingsSet('DraftFolder', oData.SystemFolders[ServerFolderType.DRAFTS] || null);
Settings.settingsSet('SpamFolder', oData.SystemFolders[ServerFolderType.JUNK] || null); Settings.settingsSet('SpamFolder', oData.SystemFolders[ServerFolderType.JUNK] || null);
@ -165,8 +170,7 @@ class PromisesUserPopulator extends AbstractBasicPromises
FolderStore.trashFolder(this.normalizeFolder(Settings.settingsGet('TrashFolder'))); FolderStore.trashFolder(this.normalizeFolder(Settings.settingsGet('TrashFolder')));
FolderStore.archiveFolder(this.normalizeFolder(Settings.settingsGet('ArchiveFolder'))); FolderStore.archiveFolder(this.normalizeFolder(Settings.settingsGet('ArchiveFolder')));
if (update) if (update) {
{
Remote.saveSystemFolders(noop, { Remote.saveSystemFolders(noop, {
SentFolder: FolderStore.sentFolder(), SentFolder: FolderStore.sentFolder(),
DraftFolder: FolderStore.draftFolder(), DraftFolder: FolderStore.draftFolder(),

View file

@ -1,19 +1,17 @@
import window from 'window'; import window from 'window';
import _ from '_'; import _ from '_';
import $ from '$'; import $ from '$';
import {TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT, DEFAULT_AJAX_TIMEOUT} from 'Common/Consts'; import { TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT, DEFAULT_AJAX_TIMEOUT } from 'Common/Consts';
import {StorageResultType, Notification} from 'Common/Enums'; import { StorageResultType, Notification } from 'Common/Enums';
import {inArray, pInt, pString, isUnd} from 'Common/Utils'; import { inArray, pInt, pString, isUnd } from 'Common/Utils';
import {data as GlobalsData} from 'Common/Globals'; import { data as GlobalsData } from 'Common/Globals';
import {ajax} from 'Common/Links'; import { ajax } from 'Common/Links';
import {runHook} from 'Common/Plugins'; import { runHook } from 'Common/Plugins';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
class AbstractAjaxRemote class AbstractAjaxRemote {
{
constructor() { constructor() {
this.oRequests = {}; this.oRequests = {};
} }
@ -27,72 +25,73 @@ class AbstractAjaxRemote
* @param {*=} oRequestParameters * @param {*=} oRequestParameters
*/ */
defaultResponse(fCallback, sRequestAction, sType, oData, bCached, oRequestParameters) { defaultResponse(fCallback, sRequestAction, sType, oData, bCached, oRequestParameters) {
const const fCall = () => {
fCall = () => { if (StorageResultType.Success !== sType && GlobalsData.bUnload) {
if (StorageResultType.Success !== sType && GlobalsData.bUnload) sType = StorageResultType.Unload;
{ }
sType = StorageResultType.Unload;
if (StorageResultType.Success === sType && oData && !oData.Result) {
if (
oData &&
-1 <
inArray(oData.ErrorCode, [
Notification.AuthError,
Notification.AccessError,
Notification.ConnectionError,
Notification.DomainNotAllowed,
Notification.AccountNotAllowed,
Notification.MailServerError,
Notification.UnknownNotification,
Notification.UnknownError
])
) {
GlobalsData.iAjaxErrorCount += 1;
} }
if (StorageResultType.Success === sType && oData && !oData.Result) if (oData && Notification.InvalidToken === oData.ErrorCode) {
{ GlobalsData.iTokenErrorCount += 1;
if (oData && -1 < inArray(oData.ErrorCode, [ }
Notification.AuthError, Notification.AccessError,
Notification.ConnectionError, Notification.DomainNotAllowed, Notification.AccountNotAllowed,
Notification.MailServerError, Notification.UnknownNotification, Notification.UnknownError
]))
{
GlobalsData.iAjaxErrorCount += 1;
}
if (oData && Notification.InvalidToken === oData.ErrorCode) if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount) {
{ if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload) {
GlobalsData.iTokenErrorCount += 1; GlobalsData.__APP__.loginAndLogoutReload(false, true);
} }
}
if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount) if (oData.ClearAuth || oData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount) {
{ if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken) {
if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload) GlobalsData.__APP__.clearClientSideToken();
{
if (!oData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload) {
GlobalsData.__APP__.loginAndLogoutReload(false, true); GlobalsData.__APP__.loginAndLogoutReload(false, true);
} }
} }
if (oData.ClearAuth || oData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount)
{
if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken)
{
GlobalsData.__APP__.clearClientSideToken();
if (!oData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload)
{
GlobalsData.__APP__.loginAndLogoutReload(false, true);
}
}
}
}
else if (StorageResultType.Success === sType && oData && oData.Result)
{
GlobalsData.iAjaxErrorCount = 0;
GlobalsData.iTokenErrorCount = 0;
} }
} else if (StorageResultType.Success === sType && oData && oData.Result) {
GlobalsData.iAjaxErrorCount = 0;
GlobalsData.iTokenErrorCount = 0;
}
runHook('ajax-default-response', [sRequestAction, StorageResultType.Success === sType ? oData : null, sType, bCached, oRequestParameters]); runHook('ajax-default-response', [
sRequestAction,
StorageResultType.Success === sType ? oData : null,
sType,
bCached,
oRequestParameters
]);
if (fCallback) if (fCallback) {
{ fCallback(
fCallback( sType,
sType, StorageResultType.Success === sType ? oData : null,
StorageResultType.Success === sType ? oData : null, bCached,
bCached, sRequestAction,
sRequestAction, oRequestParameters
oRequestParameters );
); }
} };
};
switch (sType) switch (sType) {
{
case 'success': case 'success':
sType = StorageResultType.Success; sType = StorageResultType.Success;
break; break;
@ -104,12 +103,9 @@ class AbstractAjaxRemote
break; break;
} }
if (StorageResultType.Error === sType) if (StorageResultType.Error === sType) {
{
_.delay(fCall, 300); _.delay(fCall, 300);
} } else {
else
{
fCall(); fCall();
} }
} }
@ -123,25 +119,20 @@ class AbstractAjaxRemote
* @returns {jQuery.jqXHR} * @returns {jQuery.jqXHR}
*/ */
ajaxRequest(fResultCallback, params, iTimeOut = 20000, sGetAdd = '', abortActions = []) { ajaxRequest(fResultCallback, params, iTimeOut = 20000, sGetAdd = '', abortActions = []) {
const const isPost = '' === sGetAdd,
isPost = '' === sGetAdd,
headers = {}, headers = {},
start = (new window.Date()).getTime(); start = new window.Date().getTime();
let let action = '';
action = '';
params = params || {}; params = params || {};
action = params.Action || ''; action = params.Action || '';
if (action && 0 < abortActions.length) if (action && 0 < abortActions.length) {
{
_.each(abortActions, (actionToAbort) => { _.each(abortActions, (actionToAbort) => {
if (this.oRequests[actionToAbort]) if (this.oRequests[actionToAbort]) {
{
this.oRequests[actionToAbort].__aborted = true; this.oRequests[actionToAbort].__aborted = true;
if (this.oRequests[actionToAbort].abort) if (this.oRequests[actionToAbort].abort) {
{
this.oRequests[actionToAbort].abort(); this.oRequests[actionToAbort].abort();
} }
this.oRequests[actionToAbort] = null; this.oRequests[actionToAbort] = null;
@ -149,8 +140,7 @@ class AbstractAjaxRemote
}); });
} }
if (isPost) if (isPost) {
{
params.XToken = Settings.appSettingsGet('token'); params.XToken = Settings.appSettingsGet('token');
} }
@ -166,17 +156,13 @@ class AbstractAjaxRemote
}); });
oDefAjax.always((oData, sType) => { oDefAjax.always((oData, sType) => {
let cached = false; let cached = false;
if (oData && oData.Time) if (oData && oData.Time) {
{ cached = pInt(oData.Time) > new window.Date().getTime() - start;
cached = pInt(oData.Time) > (new window.Date()).getTime() - start;
} }
if (action && this.oRequests[action]) if (action && this.oRequests[action]) {
{ if (this.oRequests[action].__aborted) {
if (this.oRequests[action].__aborted)
{
sType = 'abort'; sType = 'abort';
} }
@ -186,13 +172,10 @@ class AbstractAjaxRemote
this.defaultResponse(fResultCallback, action, sType, oData, cached, params); this.defaultResponse(fResultCallback, action, sType, oData, cached, params);
}); });
if (action && 0 < abortActions.length && -1 < inArray(action, abortActions)) if (action && 0 < abortActions.length && -1 < inArray(action, abortActions)) {
{ if (this.oRequests[action]) {
if (this.oRequests[action])
{
this.oRequests[action].__aborted = true; this.oRequests[action].__aborted = true;
if (this.oRequests[action].abort) if (this.oRequests[action].abort) {
{
this.oRequests[action].abort(); this.oRequests[action].abort();
} }
this.oRequests[action] = null; this.oRequests[action] = null;
@ -201,6 +184,7 @@ class AbstractAjaxRemote
this.oRequests[action] = oDefAjax; this.oRequests[action] = oDefAjax;
} }
// eslint-disable-next-line no-console
oDefAjax.catch(console.log); oDefAjax.catch(console.log);
return oDefAjax; return oDefAjax;
} }
@ -221,8 +205,13 @@ class AbstractAjaxRemote
runHook('ajax-default-request', [sAction, oParameters, sGetAdd]); runHook('ajax-default-request', [sAction, oParameters, sGetAdd]);
return this.ajaxRequest(fCallback, oParameters, return this.ajaxRequest(
isUnd(iTimeout) ? DEFAULT_AJAX_TIMEOUT : pInt(iTimeout), sGetAdd, aAbortActions); fCallback,
oParameters,
isUnd(iTimeout) ? DEFAULT_AJAX_TIMEOUT : pInt(iTimeout),
sGetAdd,
aAbortActions
);
} }
/** /**
@ -284,4 +273,4 @@ class AbstractAjaxRemote
} }
} }
export {AbstractAjaxRemote, AbstractAjaxRemote as default}; export { AbstractAjaxRemote, AbstractAjaxRemote as default };

View file

@ -1,8 +1,6 @@
import { AbstractAjaxRemote } from 'Remote/AbstractAjax';
import {AbstractAjaxRemote} from 'Remote/AbstractAjax'; class RemoteAdminAjax extends AbstractAjaxRemote {
class RemoteAdminAjax extends AbstractAjaxRemote
{
constructor() { constructor() {
super(); super();
@ -92,11 +90,16 @@ class RemoteAdminAjax extends AbstractAjaxRemote
* @param {Object} oPackage * @param {Object} oPackage
*/ */
packageInstall(fCallback, oPackage) { packageInstall(fCallback, oPackage) {
this.defaultRequest(fCallback, 'AdminPackageInstall', { this.defaultRequest(
'Id': oPackage.id, fCallback,
'Type': oPackage.type, 'AdminPackageInstall',
'File': oPackage.file {
}, 60000); 'Id': oPackage.id,
'Type': oPackage.type,
'File': oPackage.file
},
60000
);
} }
/** /**
@ -200,11 +203,25 @@ class RemoteAdminAjax extends AbstractAjaxRemote
}); });
} }
createOrUpdateDomain(fCallback, createOrUpdateDomain(
bCreate, sName, fCallback,
sIncHost, iIncPort, sIncSecure, bIncShortLogin, bCreate,
bUseSieve, sSieveAllowRaw, sSieveHost, iSievePort, sSieveSecure, sName,
sOutHost, iOutPort, sOutSecure, bOutShortLogin, bOutAuth, bOutPhpMail, sIncHost,
iIncPort,
sIncSecure,
bIncShortLogin,
bUseSieve,
sSieveAllowRaw,
sSieveHost,
iSievePort,
sSieveSecure,
sOutHost,
iOutPort,
sOutSecure,
bOutShortLogin,
bOutAuth,
bOutPhpMail,
sWhiteList sWhiteList
) { ) {
this.defaultRequest(fCallback, 'AdminDomainSave', { this.defaultRequest(fCallback, 'AdminDomainSave', {
@ -233,10 +250,21 @@ class RemoteAdminAjax extends AbstractAjaxRemote
}); });
} }
testConnectionForDomain(fCallback, sName, testConnectionForDomain(
sIncHost, iIncPort, sIncSecure, fCallback,
bUseSieve, sSieveHost, iSievePort, sSieveSecure, sName,
sOutHost, iOutPort, sOutSecure, bOutAuth, bOutPhpMail sIncHost,
iIncPort,
sIncSecure,
bUseSieve,
sSieveHost,
iSievePort,
sSieveSecure,
sOutHost,
iOutPort,
sOutSecure,
bOutAuth,
bOutPhpMail
) { ) {
this.defaultRequest(fCallback, 'AdminDomainTest', { this.defaultRequest(fCallback, 'AdminDomainTest', {
'Name': sName, 'Name': sName,

View file

@ -1,7 +1,6 @@
import _ from '_'; import _ from '_';
import {pString, pInt, isArray, trim, boolToAjax} from 'Common/Utils'; import { pString, pInt, isArray, trim, boolToAjax } from 'Common/Utils';
import { import {
CONTACTS_SYNC_AJAX_TIMEOUT, CONTACTS_SYNC_AJAX_TIMEOUT,
@ -19,19 +18,18 @@ import {
getMessageFlagsFromCache getMessageFlagsFromCache
} from 'Common/Cache'; } from 'Common/Cache';
import {subQueryPrefix} from 'Common/Links'; import { subQueryPrefix } from 'Common/Links';
import * as Base64 from 'Common/Base64'; import * as Base64 from 'Common/Base64';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
import AppStore from 'Stores/User/App'; import AppStore from 'Stores/User/App';
import SettingsStore from 'Stores/User/Settings'; import SettingsStore from 'Stores/User/Settings';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
import {AbstractAjaxRemote} from 'Remote/AbstractAjax'; import { AbstractAjaxRemote } from 'Remote/AbstractAjax';
class RemoteUserAjax extends AbstractAjaxRemote class RemoteUserAjax extends AbstractAjaxRemote {
{
constructor() { constructor() {
super(); super();
this.oRequests = {}; this.oRequests = {};
@ -41,13 +39,20 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {?Function} fCallback * @param {?Function} fCallback
*/ */
folders(fCallback) { folders(fCallback) {
this.defaultRequest(fCallback, 'Folders', { this.defaultRequest(
'SentFolder': Settings.settingsGet('SentFolder'), fCallback,
'DraftFolder': Settings.settingsGet('DraftFolder'), 'Folders',
'SpamFolder': Settings.settingsGet('SpamFolder'), {
'TrashFolder': Settings.settingsGet('TrashFolder'), 'SentFolder': Settings.settingsGet('SentFolder'),
'ArchiveFolder': Settings.settingsGet('ArchiveFolder') 'DraftFolder': Settings.settingsGet('DraftFolder'),
}, null, '', ['Folders']); 'SpamFolder': Settings.settingsGet('SpamFolder'),
'TrashFolder': Settings.settingsGet('TrashFolder'),
'ArchiveFolder': Settings.settingsGet('ArchiveFolder')
},
null,
'',
['Folders']
);
} }
/** /**
@ -304,40 +309,54 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {boolean=} bSilent = false * @param {boolean=} bSilent = false
*/ */
messageList(fCallback, sFolderFullNameRaw, iOffset = 0, iLimit = 20, sSearch = '', sThreadUid = '', bSilent = false) { messageList(fCallback, sFolderFullNameRaw, iOffset = 0, iLimit = 20, sSearch = '', sThreadUid = '', bSilent = false) {
sFolderFullNameRaw = pString(sFolderFullNameRaw); sFolderFullNameRaw = pString(sFolderFullNameRaw);
const const folderHash = getFolderHash(sFolderFullNameRaw),
folderHash = getFolderHash(sFolderFullNameRaw),
useThreads = AppStore.threadsAllowed() && SettingsStore.useThreads(), useThreads = AppStore.threadsAllowed() && SettingsStore.useThreads(),
inboxUidNext = getFolderInboxName() === sFolderFullNameRaw ? getFolderUidNext(sFolderFullNameRaw) : ''; inboxUidNext = getFolderInboxName() === sFolderFullNameRaw ? getFolderUidNext(sFolderFullNameRaw) : '';
if ('' !== folderHash && ('' === sSearch || -1 === sSearch.indexOf('is:'))) if ('' !== folderHash && ('' === sSearch || -1 === sSearch.indexOf('is:'))) {
{ return this.defaultRequest(
return this.defaultRequest(fCallback, 'MessageList', {}, fCallback,
'MessageList',
{},
'' === sSearch ? DEFAULT_AJAX_TIMEOUT : SEARCH_AJAX_TIMEOUT, '' === sSearch ? DEFAULT_AJAX_TIMEOUT : SEARCH_AJAX_TIMEOUT,
'MessageList/' + subQueryPrefix() + '/' + Base64.urlsafe_encode([ 'MessageList/' +
sFolderFullNameRaw, subQueryPrefix() +
iOffset, '/' +
iLimit, Base64.urlsafe_encode(
sSearch, [
AppStore.projectHash(), sFolderFullNameRaw,
folderHash, iOffset,
inboxUidNext, iLimit,
useThreads ? '1' : '0', sSearch,
useThreads ? sThreadUid : '' AppStore.projectHash(),
].join(String.fromCharCode(0))), bSilent ? [] : ['MessageList']); folderHash,
inboxUidNext,
useThreads ? '1' : '0',
useThreads ? sThreadUid : ''
].join(String.fromCharCode(0))
),
bSilent ? [] : ['MessageList']
);
} }
return this.defaultRequest(fCallback, 'MessageList', { return this.defaultRequest(
Folder: sFolderFullNameRaw, fCallback,
Offset: iOffset, 'MessageList',
Limit: iLimit, {
Search: sSearch, Folder: sFolderFullNameRaw,
UidNext: inboxUidNext, Offset: iOffset,
UseThreads: useThreads ? '1' : '0', Limit: iLimit,
ThreadUid: useThreads ? sThreadUid : '' Search: sSearch,
}, '' === sSearch ? DEFAULT_AJAX_TIMEOUT : SEARCH_AJAX_TIMEOUT, '', bSilent ? [] : ['MessageList']); UidNext: inboxUidNext,
UseThreads: useThreads ? '1' : '0',
ThreadUid: useThreads ? sThreadUid : ''
},
'' === sSearch ? DEFAULT_AJAX_TIMEOUT : SEARCH_AJAX_TIMEOUT,
'',
bSilent ? [] : ['MessageList']
);
} }
/** /**
@ -345,9 +364,14 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {Array} aDownloads * @param {Array} aDownloads
*/ */
messageUploadAttachments(fCallback, aDownloads) { messageUploadAttachments(fCallback, aDownloads) {
this.defaultRequest(fCallback, 'MessageUploadAttachments', { this.defaultRequest(
'Attachments': aDownloads fCallback,
}, 999000); 'MessageUploadAttachments',
{
'Attachments': aDownloads
},
999000
);
} }
/** /**
@ -357,19 +381,28 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @returns {boolean} * @returns {boolean}
*/ */
message(fCallback, sFolderFullNameRaw, iUid) { message(fCallback, sFolderFullNameRaw, iUid) {
sFolderFullNameRaw = pString(sFolderFullNameRaw); sFolderFullNameRaw = pString(sFolderFullNameRaw);
iUid = pInt(iUid); iUid = pInt(iUid);
if (getFolderFromCacheList(sFolderFullNameRaw) && 0 < iUid) if (getFolderFromCacheList(sFolderFullNameRaw) && 0 < iUid) {
{ this.defaultRequest(
this.defaultRequest(fCallback, 'Message', {}, null, fCallback,
'Message/' + subQueryPrefix() + '/' + Base64.urlsafe_encode([ 'Message',
sFolderFullNameRaw, {},
iUid, null,
AppStore.projectHash(), 'Message/' +
AppStore.threadsAllowed() && SettingsStore.useThreads() ? '1' : '0' subQueryPrefix() +
].join(String.fromCharCode(0))), ['Message']); '/' +
Base64.urlsafe_encode(
[
sFolderFullNameRaw,
iUid,
AppStore.projectHash(),
AppStore.threadsAllowed() && SettingsStore.useThreads() ? '1' : '0'
].join(String.fromCharCode(0))
),
['Message']
);
return true; return true;
} }
@ -382,9 +415,14 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {Array} aExternals * @param {Array} aExternals
*/ */
composeUploadExternals(fCallback, aExternals) { composeUploadExternals(fCallback, aExternals) {
this.defaultRequest(fCallback, 'ComposeUploadExternals', { this.defaultRequest(
'Externals': aExternals fCallback,
}, 999000); 'ComposeUploadExternals',
{
'Externals': aExternals
},
999000
);
} }
/** /**
@ -393,10 +431,15 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {string} sAccessToken * @param {string} sAccessToken
*/ */
composeUploadDrive(fCallback, sUrl, sAccessToken) { composeUploadDrive(fCallback, sUrl, sAccessToken) {
this.defaultRequest(fCallback, 'ComposeUploadDrive', { this.defaultRequest(
'AccessToken': sAccessToken, fCallback,
'Url': sUrl 'ComposeUploadDrive',
}, 999000); {
'AccessToken': sAccessToken,
'Url': sUrl
},
999000
);
} }
/** /**
@ -405,46 +448,37 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {Array=} list = [] * @param {Array=} list = []
*/ */
folderInformation(fCallback, folder, list = []) { folderInformation(fCallback, folder, list = []) {
let request = true; let request = true;
const uids = []; const uids = [];
if (isArray(list) && 0 < list.length) if (isArray(list) && 0 < list.length) {
{
request = false; request = false;
_.each(list, (messageListItem) => { _.each(list, (messageListItem) => {
if (!getMessageFlagsFromCache(messageListItem.folderFullNameRaw, messageListItem.uid)) if (!getMessageFlagsFromCache(messageListItem.folderFullNameRaw, messageListItem.uid)) {
{
uids.push(messageListItem.uid); uids.push(messageListItem.uid);
} }
if (0 < messageListItem.threads().length) if (0 < messageListItem.threads().length) {
{
_.each(messageListItem.threads(), (uid) => { _.each(messageListItem.threads(), (uid) => {
if (!getMessageFlagsFromCache(messageListItem.folderFullNameRaw, uid)) if (!getMessageFlagsFromCache(messageListItem.folderFullNameRaw, uid)) {
{
uids.push(uid); uids.push(uid);
} }
}); });
} }
}); });
if (0 < uids.length) if (0 < uids.length) {
{
request = true; request = true;
} }
} }
if (request) if (request) {
{
this.defaultRequest(fCallback, 'FolderInformation', { this.defaultRequest(fCallback, 'FolderInformation', {
'Folder': folder, 'Folder': folder,
'FlagsUids': isArray(uids) ? uids.join(',') : '', 'FlagsUids': isArray(uids) ? uids.join(',') : '',
'UidNext': getFolderInboxName() === folder ? getFolderUidNext(folder) : '' 'UidNext': getFolderInboxName() === folder ? getFolderUidNext(folder) : ''
}); });
} } else if (SettingsStore.useThreads()) {
else if (SettingsStore.useThreads())
{
getApp().reloadFlagsCurrentMessageListAndMessageFromCache(); getApp().reloadFlagsCurrentMessageListAndMessageFromCache();
} }
} }
@ -527,27 +561,48 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {string} sReferences * @param {string} sReferences
* @param {boolean} bMarkAsImportant * @param {boolean} bMarkAsImportant
*/ */
saveMessage(fCallback, sIdentityID, sMessageFolder, sMessageUid, sDraftFolder, saveMessage(
sTo, sCc, sBcc, sReplyTo, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences, bMarkAsImportant) { fCallback,
sIdentityID,
this.defaultRequest(fCallback, 'SaveMessage', { sMessageFolder,
'IdentityID': sIdentityID, sMessageUid,
'MessageFolder': sMessageFolder, sDraftFolder,
'MessageUid': sMessageUid, sTo,
'DraftFolder': sDraftFolder, sCc,
'To': sTo, sBcc,
'Cc': sCc, sReplyTo,
'Bcc': sBcc, sSubject,
'ReplyTo': sReplyTo, bTextIsHtml,
'Subject': sSubject, sText,
'TextIsHtml': bTextIsHtml ? '1' : '0', aAttachments,
'Text': sText, aDraftInfo,
'DraftInfo': aDraftInfo, sInReplyTo,
'InReplyTo': sInReplyTo, sReferences,
'References': sReferences, bMarkAsImportant
'MarkAsImportant': bMarkAsImportant ? '1' : '0', ) {
'Attachments': aAttachments this.defaultRequest(
}, SAVE_MESSAGE_AJAX_TIMEOUT); fCallback,
'SaveMessage',
{
'IdentityID': sIdentityID,
'MessageFolder': sMessageFolder,
'MessageUid': sMessageUid,
'DraftFolder': sDraftFolder,
'To': sTo,
'Cc': sCc,
'Bcc': sBcc,
'ReplyTo': sReplyTo,
'Subject': sSubject,
'TextIsHtml': bTextIsHtml ? '1' : '0',
'Text': sText,
'DraftInfo': aDraftInfo,
'InReplyTo': sInReplyTo,
'References': sReferences,
'MarkAsImportant': bMarkAsImportant ? '1' : '0',
'Attachments': aAttachments
},
SAVE_MESSAGE_AJAX_TIMEOUT
);
} }
/** /**
@ -589,30 +644,52 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {boolean} bRequestReadReceipt * @param {boolean} bRequestReadReceipt
* @param {boolean} bMarkAsImportant * @param {boolean} bMarkAsImportant
*/ */
sendMessage(fCallback, sIdentityID, sMessageFolder, sMessageUid, sSentFolder, sendMessage(
sTo, sCc, sBcc, sReplyTo, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences, fCallback,
bRequestDsn, bRequestReadReceipt, bMarkAsImportant) { sIdentityID,
sMessageFolder,
this.defaultRequest(fCallback, 'SendMessage', { sMessageUid,
'IdentityID': sIdentityID, sSentFolder,
'MessageFolder': sMessageFolder, sTo,
'MessageUid': sMessageUid, sCc,
'SentFolder': sSentFolder, sBcc,
'To': sTo, sReplyTo,
'Cc': sCc, sSubject,
'Bcc': sBcc, bTextIsHtml,
'ReplyTo': sReplyTo, sText,
'Subject': sSubject, aAttachments,
'TextIsHtml': bTextIsHtml ? '1' : '0', aDraftInfo,
'Text': sText, sInReplyTo,
'DraftInfo': aDraftInfo, sReferences,
'InReplyTo': sInReplyTo, bRequestDsn,
'References': sReferences, bRequestReadReceipt,
'Dsn': bRequestDsn ? '1' : '0', bMarkAsImportant
'ReadReceiptRequest': bRequestReadReceipt ? '1' : '0', ) {
'MarkAsImportant': bMarkAsImportant ? '1' : '0', this.defaultRequest(
'Attachments': aAttachments fCallback,
}, SEND_MESSAGE_AJAX_TIMEOUT); 'SendMessage',
{
'IdentityID': sIdentityID,
'MessageFolder': sMessageFolder,
'MessageUid': sMessageUid,
'SentFolder': sSentFolder,
'To': sTo,
'Cc': sCc,
'Bcc': sBcc,
'ReplyTo': sReplyTo,
'Subject': sSubject,
'TextIsHtml': bTextIsHtml ? '1' : '0',
'Text': sText,
'DraftInfo': aDraftInfo,
'InReplyTo': sInReplyTo,
'References': sReferences,
'Dsn': bRequestDsn ? '1' : '0',
'ReadReceiptRequest': bRequestReadReceipt ? '1' : '0',
'MarkAsImportant': bMarkAsImportant ? '1' : '0',
'Attachments': aAttachments
},
SEND_MESSAGE_AJAX_TIMEOUT
);
} }
/** /**
@ -699,13 +776,20 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {boolean=} bMarkAsRead * @param {boolean=} bMarkAsRead
*/ */
messagesMove(fCallback, sFolder, sToFolder, aUids, sLearning, bMarkAsRead) { messagesMove(fCallback, sFolder, sToFolder, aUids, sLearning, bMarkAsRead) {
this.defaultRequest(fCallback, 'MessageMove', { this.defaultRequest(
'FromFolder': sFolder, fCallback,
'ToFolder': sToFolder, 'MessageMove',
'Uids': aUids.join(','), {
'MarkAsRead': bMarkAsRead ? '1' : '0', 'FromFolder': sFolder,
'Learning': sLearning || '' 'ToFolder': sToFolder,
}, null, '', ['MessageList']); 'Uids': aUids.join(','),
'MarkAsRead': bMarkAsRead ? '1' : '0',
'Learning': sLearning || ''
},
null,
'',
['MessageList']
);
} }
/** /**
@ -728,10 +812,17 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {Array} aUids * @param {Array} aUids
*/ */
messagesDelete(fCallback, sFolder, aUids) { messagesDelete(fCallback, sFolder, aUids) {
this.defaultRequest(fCallback, 'MessageDelete', { this.defaultRequest(
'Folder': sFolder, fCallback,
'Uids': aUids.join(',') 'MessageDelete',
}, null, '', ['MessageList']); {
'Folder': sFolder,
'Uids': aUids.join(',')
},
null,
'',
['MessageList']
);
} }
/** /**
@ -755,11 +846,18 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {string} sSearch * @param {string} sSearch
*/ */
contacts(fCallback, iOffset, iLimit, sSearch) { contacts(fCallback, iOffset, iLimit, sSearch) {
this.defaultRequest(fCallback, 'Contacts', { this.defaultRequest(
'Offset': iOffset, fCallback,
'Limit': iLimit, 'Contacts',
'Search': sSearch {
}, null, '', ['Contacts']); 'Offset': iOffset,
'Limit': iLimit,
'Search': sSearch
},
null,
'',
['Contacts']
);
} }
/** /**
@ -792,10 +890,17 @@ class RemoteUserAjax extends AbstractAjaxRemote
* @param {number} iPage * @param {number} iPage
*/ */
suggestions(fCallback, sQuery, iPage) { suggestions(fCallback, sQuery, iPage) {
this.defaultRequest(fCallback, 'Suggestions', { this.defaultRequest(
'Query': sQuery, fCallback,
'Page': iPage 'Suggestions',
}, null, '', ['Suggestions']); {
'Query': sQuery,
'Page': iPage
},
null,
'',
['Suggestions']
);
} }
/** /**

View file

@ -1,22 +1,19 @@
import _ from '_'; import _ from '_';
import $ from '$'; import $ from '$';
import ko from 'ko'; import ko from 'ko';
import {VIEW_MODELS} from 'Common/Globals'; import { VIEW_MODELS } from 'Common/Globals';
import {delegateRun, windowResize, log, isUnd, pString} from 'Common/Utils'; import { delegateRun, windowResize, log, isUnd, pString } from 'Common/Utils';
import {settings} from 'Common/Links'; import { settings } from 'Common/Links';
import {setHash} from 'Knoin/Knoin'; import { setHash } from 'Knoin/Knoin';
import {AbstractScreen} from 'Knoin/AbstractScreen'; import { AbstractScreen } from 'Knoin/AbstractScreen';
class AbstractSettingsScreen extends AbstractScreen class AbstractSettingsScreen extends AbstractScreen {
{
/** /**
* @param {Array} viewModels * @param {Array} viewModels
*/ */
constructor(viewModels) constructor(viewModels) {
{
super('settings', viewModels); super('settings', viewModels);
this.menu = ko.observableArray([]); this.menu = ko.observableArray([]);
@ -31,51 +28,57 @@ class AbstractSettingsScreen extends AbstractScreen
* @param {Function=} fCallback * @param {Function=} fCallback
*/ */
setupSettings(fCallback = null) { setupSettings(fCallback = null) {
if (fCallback) if (fCallback) {
{
fCallback(); fCallback();
} }
} }
onRoute(subName) { onRoute(subName) {
let let settingsScreen = null,
settingsScreen = null,
RoutedSettingsViewModel = null, RoutedSettingsViewModel = null,
viewModelPlace = null, viewModelPlace = null,
viewModelDom = null; viewModelDom = null;
RoutedSettingsViewModel = _.find(VIEW_MODELS.settings, RoutedSettingsViewModel = _.find(
(SettingsViewModel) => SettingsViewModel && SettingsViewModel.__rlSettingsData && subName === SettingsViewModel.__rlSettingsData.Route VIEW_MODELS.settings,
(SettingsViewModel) =>
SettingsViewModel && SettingsViewModel.__rlSettingsData && subName === SettingsViewModel.__rlSettingsData.Route
); );
if (RoutedSettingsViewModel) if (RoutedSettingsViewModel) {
{ if (
if (_.find(VIEW_MODELS['settings-removed'], (DisabledSettingsViewModel) => DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel)) _.find(
{ VIEW_MODELS['settings-removed'],
(DisabledSettingsViewModel) =>
DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel
)
) {
RoutedSettingsViewModel = null; RoutedSettingsViewModel = null;
} }
if (RoutedSettingsViewModel && _.find(VIEW_MODELS['settings-disabled'], if (
(DisabledSettingsViewModel) => DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel)) RoutedSettingsViewModel &&
{ _.find(
VIEW_MODELS['settings-disabled'],
(DisabledSettingsViewModel) =>
DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel
)
) {
RoutedSettingsViewModel = null; RoutedSettingsViewModel = null;
} }
} }
if (RoutedSettingsViewModel) if (RoutedSettingsViewModel) {
{ if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm) {
if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm)
{
settingsScreen = RoutedSettingsViewModel.__vm; settingsScreen = RoutedSettingsViewModel.__vm;
} } else {
else
{
viewModelPlace = this.oViewModelPlace; viewModelPlace = this.oViewModelPlace;
if (viewModelPlace && 1 === viewModelPlace.length) if (viewModelPlace && 1 === viewModelPlace.length) {
{
settingsScreen = new RoutedSettingsViewModel(); settingsScreen = new RoutedSettingsViewModel();
viewModelDom = $('<div></div>').addClass('rl-settings-view-model').hide(); viewModelDom = $('<div></div>')
.addClass('rl-settings-view-model')
.hide();
viewModelDom.appendTo(viewModelPlace); viewModelDom.appendTo(viewModelPlace);
settingsScreen.viewModelDom = viewModelDom; settingsScreen.viewModelDom = viewModelDom;
@ -86,26 +89,26 @@ class AbstractSettingsScreen extends AbstractScreen
RoutedSettingsViewModel.__builded = true; RoutedSettingsViewModel.__builded = true;
RoutedSettingsViewModel.__vm = settingsScreen; RoutedSettingsViewModel.__vm = settingsScreen;
const tmpl = {name: RoutedSettingsViewModel.__rlSettingsData.Template}; const tmpl = { name: RoutedSettingsViewModel.__rlSettingsData.Template };
ko.applyBindingAccessorsToNode(viewModelDom[0], { ko.applyBindingAccessorsToNode(
translatorInit: true, viewModelDom[0],
template: () => tmpl {
}, settingsScreen); translatorInit: true,
template: () => tmpl
},
settingsScreen
);
delegateRun(settingsScreen, 'onBuild', [viewModelDom]); delegateRun(settingsScreen, 'onBuild', [viewModelDom]);
} } else {
else
{
log('Cannot find sub settings view model position: SettingsSubScreen'); log('Cannot find sub settings view model position: SettingsSubScreen');
} }
} }
if (settingsScreen) if (settingsScreen) {
{
_.defer(() => { _.defer(() => {
// hide // hide
if (this.oCurrentSubScreen) if (this.oCurrentSubScreen) {
{
delegateRun(this.oCurrentSubScreen, 'onHide'); delegateRun(this.oCurrentSubScreen, 'onHide');
this.oCurrentSubScreen.viewModelDom.hide(); this.oCurrentSubScreen.viewModelDom.hide();
} }
@ -114,15 +117,18 @@ class AbstractSettingsScreen extends AbstractScreen
this.oCurrentSubScreen = settingsScreen; this.oCurrentSubScreen = settingsScreen;
// show // show
if (this.oCurrentSubScreen) if (this.oCurrentSubScreen) {
{
delegateRun(this.oCurrentSubScreen, 'onBeforeShow'); delegateRun(this.oCurrentSubScreen, 'onBeforeShow');
this.oCurrentSubScreen.viewModelDom.show(); this.oCurrentSubScreen.viewModelDom.show();
delegateRun(this.oCurrentSubScreen, 'onShow'); delegateRun(this.oCurrentSubScreen, 'onShow');
delegateRun(this.oCurrentSubScreen, 'onShowWithDelay', [], 200); delegateRun(this.oCurrentSubScreen, 'onShowWithDelay', [], 200);
_.each(this.menu(), (item) => { _.each(this.menu(), (item) => {
item.selected(settingsScreen && settingsScreen.__rlSettingsData && item.route === settingsScreen.__rlSettingsData.Route); item.selected(
settingsScreen &&
settingsScreen.__rlSettingsData &&
item.route === settingsScreen.__rlSettingsData.Route
);
}); });
$('#rl-content .b-settings .b-content .content').scrollTop(0); $('#rl-content .b-settings .b-content .content').scrollTop(0);
@ -132,16 +138,13 @@ class AbstractSettingsScreen extends AbstractScreen
windowResize(); windowResize();
}); });
} }
} } else {
else
{
setHash(settings(), false, true); setHash(settings(), false, true);
} }
} }
onHide() { onHide() {
if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom) if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom) {
{
delegateRun(this.oCurrentSubScreen, 'onHide'); delegateRun(this.oCurrentSubScreen, 'onHide');
this.oCurrentSubScreen.viewModelDom.hide(); this.oCurrentSubScreen.viewModelDom.hide();
} }
@ -149,15 +152,22 @@ class AbstractSettingsScreen extends AbstractScreen
onBuild() { onBuild() {
_.each(VIEW_MODELS.settings, (SettingsViewModel) => { _.each(VIEW_MODELS.settings, (SettingsViewModel) => {
if (SettingsViewModel && SettingsViewModel.__rlSettingsData && !_.find(VIEW_MODELS['settings-removed'], if (
(RemoveSettingsViewModel) => RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel)) SettingsViewModel &&
{ SettingsViewModel.__rlSettingsData &&
!_.find(
VIEW_MODELS['settings-removed'],
(RemoveSettingsViewModel) => RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel
)
) {
this.menu.push({ this.menu.push({
route: SettingsViewModel.__rlSettingsData.Route, route: SettingsViewModel.__rlSettingsData.Route,
label: SettingsViewModel.__rlSettingsData.Label, label: SettingsViewModel.__rlSettingsData.Label,
selected: ko.observable(false), selected: ko.observable(false),
disabled: !!_.find(VIEW_MODELS['settings-disabled'], disabled: !!_.find(
(DisabledSettingsViewModel) => DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel) VIEW_MODELS['settings-disabled'],
(DisabledSettingsViewModel) => DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel
)
}); });
} }
}); });
@ -166,12 +176,13 @@ class AbstractSettingsScreen extends AbstractScreen
} }
routes() { routes() {
const const DefaultViewModel = _.find(
DefaultViewModel = _.find(
VIEW_MODELS.settings, VIEW_MODELS.settings,
(SettingsViewModel) => SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData.IsDefault (SettingsViewModel) =>
SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData.IsDefault
), ),
defaultRoute = DefaultViewModel && DefaultViewModel.__rlSettingsData ? DefaultViewModel.__rlSettingsData.Route : 'general', defaultRoute =
DefaultViewModel && DefaultViewModel.__rlSettingsData ? DefaultViewModel.__rlSettingsData.Route : 'general',
rules = { rules = {
subname: /^(.*)$/, subname: /^(.*)$/,
normalize_: (rquest, vals) => { normalize_: (rquest, vals) => {
@ -180,12 +191,8 @@ class AbstractSettingsScreen extends AbstractScreen
} }
}; };
return [ return [['{subname}/', rules], ['{subname}', rules], ['', rules]];
['{subname}/', rules],
['{subname}', rules],
['', rules]
];
} }
} }
export {AbstractSettingsScreen, AbstractSettingsScreen as default}; export { AbstractSettingsScreen, AbstractSettingsScreen as default };

View file

@ -1,16 +1,12 @@
import { AbstractScreen } from 'Knoin/AbstractScreen';
import {AbstractScreen} from 'Knoin/AbstractScreen'; import { getApp } from 'Helper/Apps/Admin';
import {getApp} from 'Helper/Apps/Admin'; import { LoginAdminView } from 'View/Admin/Login';
import {LoginAdminView} from 'View/Admin/Login'; class LoginAdminScreen extends AbstractScreen {
class LoginAdminScreen extends AbstractScreen
{
constructor() { constructor() {
super('login', [ super('login', [LoginAdminView]);
LoginAdminView
]);
} }
onShow() { onShow() {
@ -18,4 +14,4 @@ class LoginAdminScreen extends AbstractScreen
} }
} }
export {LoginAdminScreen, LoginAdminScreen as default}; export { LoginAdminScreen, LoginAdminScreen as default };

View file

@ -1,93 +1,82 @@
import {addSettingsViewModel} from 'Knoin/Knoin'; import { addSettingsViewModel } from 'Knoin/Knoin';
import {runSettingsViewModelHooks} from 'Common/Plugins'; import { runSettingsViewModelHooks } from 'Common/Plugins';
import {AbstractSettingsScreen} from 'Screen/AbstractSettings'; import { AbstractSettingsScreen } from 'Screen/AbstractSettings';
import {GeneralAdminSettings} from 'Settings/Admin/General'; import { GeneralAdminSettings } from 'Settings/Admin/General';
import {DomainsAdminSettings} from 'Settings/Admin/Domains'; import { DomainsAdminSettings } from 'Settings/Admin/Domains';
import {LoginAdminSettings} from 'Settings/Admin/Login'; import { LoginAdminSettings } from 'Settings/Admin/Login';
import {ContactsAdminSettings} from 'Settings/Admin/Contacts'; import { ContactsAdminSettings } from 'Settings/Admin/Contacts';
import {SecurityAdminSettings} from 'Settings/Admin/Security'; import { SecurityAdminSettings } from 'Settings/Admin/Security';
import {SocialAdminSettings} from 'Settings/Admin/Social'; import { SocialAdminSettings } from 'Settings/Admin/Social';
import {PluginsAdminSettings} from 'Settings/Admin/Plugins'; import { PluginsAdminSettings } from 'Settings/Admin/Plugins';
import {PackagesAdminSettings} from 'Settings/Admin/Packages'; import { PackagesAdminSettings } from 'Settings/Admin/Packages';
import {AboutAdminSettings} from 'Settings/Admin/About'; import { AboutAdminSettings } from 'Settings/Admin/About';
import {getApp} from 'Helper/Apps/Admin'; import { getApp } from 'Helper/Apps/Admin';
import {MenuSettingsAdminView} from 'View/Admin/Settings/Menu'; import { MenuSettingsAdminView } from 'View/Admin/Settings/Menu';
import {PaneSettingsAdminView} from 'View/Admin/Settings/Pane'; import { PaneSettingsAdminView } from 'View/Admin/Settings/Pane';
class SettingsAdminScreen extends AbstractSettingsScreen class SettingsAdminScreen extends AbstractSettingsScreen {
{
constructor() { constructor() {
super([ super([MenuSettingsAdminView, PaneSettingsAdminView]);
MenuSettingsAdminView,
PaneSettingsAdminView
]);
} }
/** /**
* @param {Function=} fCallback = null * @param {Function=} fCallback = null
*/ */
setupSettings(fCallback = null) { setupSettings(fCallback = null) {
let branding = null, let branding = null,
licensing = null; licensing = null;
if (RL_COMMUNITY) if (RL_COMMUNITY) {
{
branding = require('Settings/Admin/Branding').default; branding = require('Settings/Admin/Branding').default;
} } else {
else
{
branding = require('Settings/Admin/Prem/Branding').default; branding = require('Settings/Admin/Prem/Branding').default;
licensing = require('Settings/Admin/Prem/Licensing').default; licensing = require('Settings/Admin/Prem/Licensing').default;
} }
addSettingsViewModel(GeneralAdminSettings, addSettingsViewModel(
'AdminSettingsGeneral', 'TABS_LABELS/LABEL_GENERAL_NAME', 'general', true); GeneralAdminSettings,
'AdminSettingsGeneral',
'TABS_LABELS/LABEL_GENERAL_NAME',
'general',
true
);
addSettingsViewModel(DomainsAdminSettings, addSettingsViewModel(DomainsAdminSettings, 'AdminSettingsDomains', 'TABS_LABELS/LABEL_DOMAINS_NAME', 'domains');
'AdminSettingsDomains', 'TABS_LABELS/LABEL_DOMAINS_NAME', 'domains');
addSettingsViewModel(LoginAdminSettings, addSettingsViewModel(LoginAdminSettings, 'AdminSettingsLogin', 'TABS_LABELS/LABEL_LOGIN_NAME', 'login');
'AdminSettingsLogin', 'TABS_LABELS/LABEL_LOGIN_NAME', 'login');
if (branding) if (branding) {
{ addSettingsViewModel(branding, 'AdminSettingsBranding', 'TABS_LABELS/LABEL_BRANDING_NAME', 'branding');
addSettingsViewModel(branding,
'AdminSettingsBranding', 'TABS_LABELS/LABEL_BRANDING_NAME', 'branding');
} }
addSettingsViewModel(ContactsAdminSettings, addSettingsViewModel(ContactsAdminSettings, 'AdminSettingsContacts', 'TABS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
'AdminSettingsContacts', 'TABS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
addSettingsViewModel(SecurityAdminSettings, addSettingsViewModel(SecurityAdminSettings, 'AdminSettingsSecurity', 'TABS_LABELS/LABEL_SECURITY_NAME', 'security');
'AdminSettingsSecurity', 'TABS_LABELS/LABEL_SECURITY_NAME', 'security');
addSettingsViewModel(SocialAdminSettings, addSettingsViewModel(
'AdminSettingsSocial', 'TABS_LABELS/LABEL_INTEGRATION_NAME', 'integrations'); SocialAdminSettings,
'AdminSettingsSocial',
'TABS_LABELS/LABEL_INTEGRATION_NAME',
'integrations'
);
addSettingsViewModel(PluginsAdminSettings, addSettingsViewModel(PluginsAdminSettings, 'AdminSettingsPlugins', 'TABS_LABELS/LABEL_PLUGINS_NAME', 'plugins');
'AdminSettingsPlugins', 'TABS_LABELS/LABEL_PLUGINS_NAME', 'plugins');
addSettingsViewModel(PackagesAdminSettings, addSettingsViewModel(PackagesAdminSettings, 'AdminSettingsPackages', 'TABS_LABELS/LABEL_PACKAGES_NAME', 'packages');
'AdminSettingsPackages', 'TABS_LABELS/LABEL_PACKAGES_NAME', 'packages');
if (licensing) if (licensing) {
{ addSettingsViewModel(licensing, 'AdminSettingsLicensing', 'TABS_LABELS/LABEL_LICENSING_NAME', 'licensing');
addSettingsViewModel(licensing,
'AdminSettingsLicensing', 'TABS_LABELS/LABEL_LICENSING_NAME', 'licensing');
} }
addSettingsViewModel(AboutAdminSettings, addSettingsViewModel(AboutAdminSettings, 'AdminSettingsAbout', 'TABS_LABELS/LABEL_ABOUT_NAME', 'about');
'AdminSettingsAbout', 'TABS_LABELS/LABEL_ABOUT_NAME', 'about');
runSettingsViewModelHooks(true); runSettingsViewModelHooks(true);
if (fCallback) if (fCallback) {
{
fCallback(); fCallback();
} }
} }
@ -97,4 +86,4 @@ class SettingsAdminScreen extends AbstractSettingsScreen
} }
} }
export {SettingsAdminScreen, SettingsAdminScreen as default}; export { SettingsAdminScreen, SettingsAdminScreen as default };

View file

@ -1,12 +1,10 @@
import { AbstractScreen } from 'Knoin/AbstractScreen';
import {AbstractScreen} from 'Knoin/AbstractScreen'; import { AboutUserView } from 'View/User/About';
import {AboutUserView} from 'View/User/About'; import { getApp } from 'Helper/Apps/User';
import {getApp} from 'Helper/Apps/User'; class AboutUserScreen extends AbstractScreen {
class AboutUserScreen extends AbstractScreen
{
constructor() { constructor() {
super('about', [AboutUserView]); super('about', [AboutUserView]);
} }
@ -16,4 +14,4 @@ class AboutUserScreen extends AbstractScreen
} }
} }
export {AboutUserScreen, AboutUserScreen as default}; export { AboutUserScreen, AboutUserScreen as default };

View file

@ -1,12 +1,10 @@
import { AbstractScreen } from 'Knoin/AbstractScreen';
import {AbstractScreen} from 'Knoin/AbstractScreen'; import { LoginUserView } from 'View/User/Login';
import {LoginUserView} from 'View/User/Login'; import { getApp } from 'Helper/Apps/User';
import {getApp} from 'Helper/Apps/User'; class LoginUserScreen extends AbstractScreen {
class LoginUserScreen extends AbstractScreen
{
constructor() { constructor() {
super('login', [LoginUserView]); super('login', [LoginUserView]);
} }
@ -16,4 +14,4 @@ class LoginUserScreen extends AbstractScreen
} }
} }
export {LoginUserScreen, LoginUserScreen as default}; export { LoginUserScreen, LoginUserScreen as default };

View file

@ -1,11 +1,10 @@
import _ from '_'; import _ from '_';
import {Focused, Capa, ClientSideKeyName, Magics} from 'Common/Enums'; import { Focused, Capa, ClientSideKeyName, Magics } from 'Common/Enums';
import {$html, leftPanelDisabled, leftPanelType, moveAction, bMobileDevice} from 'Common/Globals'; import { $html, leftPanelDisabled, leftPanelType, moveAction, bMobileDevice } from 'Common/Globals';
import {pString, pInt, decodeURI, windowResizeCallback} from 'Common/Utils'; import { pString, pInt, decodeURI, windowResizeCallback } from 'Common/Utils';
import {getFolderFromCacheList, getFolderFullNameRaw, getFolderInboxName} from 'Common/Cache'; import { getFolderFromCacheList, getFolderFullNameRaw, getFolderInboxName } from 'Common/Cache';
import {i18n} from 'Common/Translator'; import { i18n } from 'Common/Translator';
import * as Events from 'Common/Events'; import * as Events from 'Common/Events';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
@ -16,19 +15,18 @@ import SettingsStore from 'Stores/User/Settings';
import FolderStore from 'Stores/User/Folder'; import FolderStore from 'Stores/User/Folder';
import MessageStore from 'Stores/User/Message'; import MessageStore from 'Stores/User/Message';
import {SystemDropDownMailBoxUserView} from 'View/User/MailBox/SystemDropDown'; import { SystemDropDownMailBoxUserView } from 'View/User/MailBox/SystemDropDown';
import {FolderListMailBoxUserView} from 'View/User/MailBox/FolderList'; import { FolderListMailBoxUserView } from 'View/User/MailBox/FolderList';
import {MessageListMailBoxUserView} from 'View/User/MailBox/MessageList'; import { MessageListMailBoxUserView } from 'View/User/MailBox/MessageList';
import {MessageViewMailBoxUserView} from 'View/User/MailBox/MessageView'; import { MessageViewMailBoxUserView } from 'View/User/MailBox/MessageView';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
import {warmUpScreenPopup} from 'Knoin/Knoin'; import { warmUpScreenPopup } from 'Knoin/Knoin';
import {AbstractScreen} from 'Knoin/AbstractScreen'; import { AbstractScreen } from 'Knoin/AbstractScreen';
class MailBoxUserScreen extends AbstractScreen class MailBoxUserScreen extends AbstractScreen {
{
constructor() { constructor() {
super('mailbox', [ super('mailbox', [
SystemDropDownMailBoxUserView, SystemDropDownMailBoxUserView,
@ -45,12 +43,16 @@ class MailBoxUserScreen extends AbstractScreen
let foldersInboxUnreadCount = FolderStore.foldersInboxUnreadCount(); let foldersInboxUnreadCount = FolderStore.foldersInboxUnreadCount();
const email = AccountStore.email(); const email = AccountStore.email();
if (Settings.appSettingsGet('listPermanentFiltered')) if (Settings.appSettingsGet('listPermanentFiltered')) {
{
foldersInboxUnreadCount = 0; foldersInboxUnreadCount = 0;
} }
getApp().setWindowTitle(('' === email ? '' : '' + (0 < foldersInboxUnreadCount ? '(' + foldersInboxUnreadCount + ') ' : ' ') + email + ' - ') + i18n('TITLES/MAILBOX')); getApp().setWindowTitle(
('' === email
? ''
: '' + (0 < foldersInboxUnreadCount ? '(' + foldersInboxUnreadCount + ') ' : ' ') + email + ' - ') +
i18n('TITLES/MAILBOX')
);
} }
/** /**
@ -62,17 +64,13 @@ class MailBoxUserScreen extends AbstractScreen
AppStore.focusedState(Focused.None); AppStore.focusedState(Focused.None);
AppStore.focusedState(Focused.MessageList); AppStore.focusedState(Focused.MessageList);
if (Settings.appSettingsGet('mobile')) if (Settings.appSettingsGet('mobile')) {
{
leftPanelDisabled(true); leftPanelDisabled(true);
} }
if (!Settings.capa(Capa.Folders)) if (!Settings.capa(Capa.Folders)) {
{
leftPanelType(Settings.capa(Capa.Composer) || Settings.capa(Capa.Contacts) ? 'short' : 'none'); leftPanelType(Settings.capa(Capa.Composer) || Settings.capa(Capa.Contacts) ? 'short' : 'none');
} } else {
else
{
leftPanelType(''); leftPanelType('');
} }
} }
@ -87,10 +85,8 @@ class MailBoxUserScreen extends AbstractScreen
let threadUid = folderHash.replace(/^(.+)~([\d]+)$/, '$2'); let threadUid = folderHash.replace(/^(.+)~([\d]+)$/, '$2');
const folder = getFolderFromCacheList(getFolderFullNameRaw(folderHash.replace(/~([\d]+)$/, ''))); const folder = getFolderFromCacheList(getFolderFullNameRaw(folderHash.replace(/~([\d]+)$/, '')));
if (folder) if (folder) {
{ if (folderHash === threadUid) {
if (folderHash === threadUid)
{
threadUid = ''; threadUid = '';
} }
@ -121,8 +117,7 @@ class MailBoxUserScreen extends AbstractScreen
const email = AccountStore.email(); const email = AccountStore.email();
_.each(AccountStore.accounts(), (item) => { _.each(AccountStore.accounts(), (item) => {
if (item && email === item.email) if (item && email === item.email) {
{
item.count(count); item.count(count);
} }
}); });
@ -135,8 +130,7 @@ class MailBoxUserScreen extends AbstractScreen
* @returns {void} * @returns {void}
*/ */
onBuild() { onBuild() {
if (!bMobileDevice && !Settings.appSettingsGet('mobile')) if (!bMobileDevice && !Settings.appSettingsGet('mobile')) {
{
_.defer(() => { _.defer(() => {
getApp().initHorizontalLayoutResizer(ClientSideKeyName.MessageListSize); getApp().initHorizontalLayoutResizer(ClientSideKeyName.MessageListSize);
}); });
@ -151,16 +145,14 @@ class MailBoxUserScreen extends AbstractScreen
* @returns {Array} * @returns {Array}
*/ */
routes() { routes() {
const const inboxFolderName = getFolderInboxName(),
inboxFolderName = getFolderInboxName(),
fNormS = (request, vals) => { fNormS = (request, vals) => {
vals[0] = pString(vals[0]); vals[0] = pString(vals[0]);
vals[1] = pInt(vals[1]); vals[1] = pInt(vals[1]);
vals[1] = 0 >= vals[1] ? 1 : vals[1]; vals[1] = 0 >= vals[1] ? 1 : vals[1];
vals[2] = pString(vals[2]); vals[2] = pString(vals[2]);
if ('' === request) if ('' === request) {
{
vals[0] = inboxFolderName; vals[0] = inboxFolderName;
vals[1] = 1; vals[1] = 1;
} }
@ -171,8 +163,7 @@ class MailBoxUserScreen extends AbstractScreen
vals[0] = pString(vals[0]); vals[0] = pString(vals[0]);
vals[1] = pString(vals[1]); vals[1] = pString(vals[1]);
if ('' === request) if ('' === request) {
{
vals[0] = inboxFolderName; vals[0] = inboxFolderName;
} }
@ -180,12 +171,12 @@ class MailBoxUserScreen extends AbstractScreen
}; };
return [ return [
[/^([a-zA-Z0-9~]+)\/p([1-9][0-9]*)\/(.+)\/?$/, {'normalize_': fNormS}], [/^([a-zA-Z0-9~]+)\/p([1-9][0-9]*)\/(.+)\/?$/, { 'normalize_': fNormS }],
[/^([a-zA-Z0-9~]+)\/p([1-9][0-9]*)$/, {'normalize_': fNormS}], [/^([a-zA-Z0-9~]+)\/p([1-9][0-9]*)$/, { 'normalize_': fNormS }],
[/^([a-zA-Z0-9~]+)\/(.+)\/?$/, {'normalize_': fNormD}], [/^([a-zA-Z0-9~]+)\/(.+)\/?$/, { 'normalize_': fNormD }],
[/^([^\/]*)$/, {'normalize_': fNormS}] [/^([^/]*)$/, { 'normalize_': fNormS }]
]; ];
} }
} }
export {MailBoxUserScreen, MailBoxUserScreen as default}; export { MailBoxUserScreen, MailBoxUserScreen as default };

View file

@ -1,135 +1,127 @@
import { Capa, KeyState } from 'Common/Enums';
import {Capa, KeyState} from 'Common/Enums'; import { keyScope, leftPanelType, leftPanelDisabled } from 'Common/Globals';
import {keyScope, leftPanelType, leftPanelDisabled} from 'Common/Globals'; import { runSettingsViewModelHooks } from 'Common/Plugins';
import {runSettingsViewModelHooks} from 'Common/Plugins'; import { initOnStartOrLangChange, i18n } from 'Common/Translator';
import {initOnStartOrLangChange, i18n} from 'Common/Translator';
import AppStore from 'Stores/User/App'; import AppStore from 'Stores/User/App';
import AccountStore from 'Stores/User/Account'; import AccountStore from 'Stores/User/Account';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
import {addSettingsViewModel} from 'Knoin/Knoin'; import { addSettingsViewModel } from 'Knoin/Knoin';
import {AbstractSettingsScreen} from 'Screen/AbstractSettings'; import { AbstractSettingsScreen } from 'Screen/AbstractSettings';
import {GeneralUserSettings} from 'Settings/User/General'; import { GeneralUserSettings } from 'Settings/User/General';
import {ContactsUserSettings} from 'Settings/User/Contacts'; import { ContactsUserSettings } from 'Settings/User/Contacts';
import {AccountsUserSettings} from 'Settings/User/Accounts'; import { AccountsUserSettings } from 'Settings/User/Accounts';
import {FiltersUserSettings} from 'Settings/User/Filters'; import { FiltersUserSettings } from 'Settings/User/Filters';
import {SecurityUserSettings} from 'Settings/User/Security'; import { SecurityUserSettings } from 'Settings/User/Security';
import {SocialUserSettings} from 'Settings/User/Social'; import { SocialUserSettings } from 'Settings/User/Social';
import {ChangePasswordUserSettings} from 'Settings/User/ChangePassword'; import { ChangePasswordUserSettings } from 'Settings/User/ChangePassword';
import {TemplatesUserSettings} from 'Settings/User/Templates'; import { TemplatesUserSettings } from 'Settings/User/Templates';
import {FoldersUserSettings} from 'Settings/User/Folders'; import { FoldersUserSettings } from 'Settings/User/Folders';
import {ThemesUserSettings} from 'Settings/User/Themes'; import { ThemesUserSettings } from 'Settings/User/Themes';
import {OpenPgpUserSettings} from 'Settings/User/OpenPgp'; import { OpenPgpUserSettings } from 'Settings/User/OpenPgp';
import {SystemDropDownSettingsUserView} from 'View/User/Settings/SystemDropDown'; import { SystemDropDownSettingsUserView } from 'View/User/Settings/SystemDropDown';
import {MenuSettingsUserView} from 'View/User/Settings/Menu'; import { MenuSettingsUserView } from 'View/User/Settings/Menu';
import {PaneSettingsUserView} from 'View/User/Settings/Pane'; import { PaneSettingsUserView } from 'View/User/Settings/Pane';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
class SettingsUserScreen extends AbstractSettingsScreen class SettingsUserScreen extends AbstractSettingsScreen {
{
constructor() { constructor() {
super([ super([SystemDropDownSettingsUserView, MenuSettingsUserView, PaneSettingsUserView]);
SystemDropDownSettingsUserView,
MenuSettingsUserView,
PaneSettingsUserView
]);
initOnStartOrLangChange(() => { initOnStartOrLangChange(
this.sSettingsTitle = i18n('TITLES/SETTINGS'); () => {
}, () => { this.sSettingsTitle = i18n('TITLES/SETTINGS');
this.setSettingsTitle(); },
}); () => {
this.setSettingsTitle();
}
);
} }
/** /**
* @param {Function=} fCallback * @param {Function=} fCallback
*/ */
setupSettings(fCallback = null) { setupSettings(fCallback = null) {
if (!Settings.capa(Capa.Settings)) if (!Settings.capa(Capa.Settings)) {
{ if (fCallback) {
if (fCallback)
{
fCallback(); fCallback();
} }
return false; return false;
} }
addSettingsViewModel(GeneralUserSettings, addSettingsViewModel(GeneralUserSettings, 'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true);
'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true);
if (AppStore.contactsIsAllowed()) if (AppStore.contactsIsAllowed()) {
{ addSettingsViewModel(ContactsUserSettings, 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
addSettingsViewModel(ContactsUserSettings,
'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
} }
if (Settings.capa(Capa.AdditionalAccounts) || Settings.capa(Capa.Identities)) if (Settings.capa(Capa.AdditionalAccounts) || Settings.capa(Capa.Identities)) {
{ addSettingsViewModel(
addSettingsViewModel(AccountsUserSettings, 'SettingsAccounts', AccountsUserSettings,
Settings.capa(Capa.AdditionalAccounts) ? 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME' : 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'accounts'); 'SettingsAccounts',
Settings.capa(Capa.AdditionalAccounts)
? 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME'
: 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME',
'accounts'
);
} }
if (Settings.capa(Capa.Sieve)) if (Settings.capa(Capa.Sieve)) {
{ addSettingsViewModel(FiltersUserSettings, 'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters');
addSettingsViewModel(FiltersUserSettings,
'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters');
} }
if (Settings.capa(Capa.AutoLogout) || Settings.capa(Capa.TwoFactor)) if (Settings.capa(Capa.AutoLogout) || Settings.capa(Capa.TwoFactor)) {
{ addSettingsViewModel(SecurityUserSettings, 'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security');
addSettingsViewModel(SecurityUserSettings,
'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security');
} }
if (AccountStore.isRootAccount() && ( if (
(Settings.settingsGet('AllowGoogleSocial') && Settings.settingsGet('AllowGoogleSocialAuth')) || AccountStore.isRootAccount() &&
Settings.settingsGet('AllowFacebookSocial') || ((Settings.settingsGet('AllowGoogleSocial') && Settings.settingsGet('AllowGoogleSocialAuth')) ||
Settings.settingsGet('AllowTwitterSocial'))) Settings.settingsGet('AllowFacebookSocial') ||
{ Settings.settingsGet('AllowTwitterSocial'))
addSettingsViewModel(SocialUserSettings, ) {
'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social'); addSettingsViewModel(SocialUserSettings, 'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social');
} }
if (Settings.settingsGet('ChangePasswordIsAllowed')) if (Settings.settingsGet('ChangePasswordIsAllowed')) {
{ addSettingsViewModel(
addSettingsViewModel(ChangePasswordUserSettings, ChangePasswordUserSettings,
'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password'); 'SettingsChangePassword',
'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME',
'change-password'
);
} }
if (Settings.capa(Capa.Templates)) if (Settings.capa(Capa.Templates)) {
{ addSettingsViewModel(
addSettingsViewModel(TemplatesUserSettings, TemplatesUserSettings,
'SettingsTemplates', 'SETTINGS_LABELS/LABEL_TEMPLATES_NAME', 'templates'); 'SettingsTemplates',
'SETTINGS_LABELS/LABEL_TEMPLATES_NAME',
'templates'
);
} }
if (Settings.capa(Capa.Folders)) if (Settings.capa(Capa.Folders)) {
{ addSettingsViewModel(FoldersUserSettings, 'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders');
addSettingsViewModel(FoldersUserSettings,
'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders');
} }
if (Settings.capa(Capa.Themes)) if (Settings.capa(Capa.Themes)) {
{ addSettingsViewModel(ThemesUserSettings, 'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes');
addSettingsViewModel(ThemesUserSettings,
'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes');
} }
if (Settings.capa(Capa.OpenPGP)) if (Settings.capa(Capa.OpenPGP)) {
{ addSettingsViewModel(OpenPgpUserSettings, 'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp');
addSettingsViewModel(OpenPgpUserSettings,
'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp');
} }
runSettingsViewModelHooks(false); runSettingsViewModelHooks(false);
if (fCallback) if (fCallback) {
{
fCallback(); fCallback();
} }
@ -141,8 +133,7 @@ class SettingsUserScreen extends AbstractSettingsScreen
keyScope(KeyState.Settings); keyScope(KeyState.Settings);
leftPanelType(''); leftPanelType('');
if (Settings.appSettingsGet('mobile')) if (Settings.appSettingsGet('mobile')) {
{
leftPanelDisabled(true); leftPanelDisabled(true);
} }
} }
@ -153,4 +144,4 @@ class SettingsUserScreen extends AbstractSettingsScreen
} }
} }
export {SettingsUserScreen, SettingsUserScreen as default}; export { SettingsUserScreen, SettingsUserScreen as default };

View file

@ -1,15 +1,14 @@
import ko from 'ko'; import ko from 'ko';
import {i18n, trigger as translatorTrigger} from 'Common/Translator'; import { i18n, trigger as translatorTrigger } from 'Common/Translator';
import {appSettingsGet, settingsGet} from 'Storage/Settings'; import { appSettingsGet, settingsGet } from 'Storage/Settings';
import AppStore from 'Stores/Admin/App'; import AppStore from 'Stores/Admin/App';
import CoreStore from 'Stores/Admin/Core'; import CoreStore from 'Stores/Admin/Core';
import {getApp} from 'Helper/Apps/Admin'; import { getApp } from 'Helper/Apps/Admin';
class AboutAdminSettings class AboutAdminSettings {
{
constructor() { constructor() {
this.version = ko.observable(appSettingsGet('version')); this.version = ko.observable(appSettingsGet('version'));
this.access = ko.observable(!!settingsGet('CoreAccess')); this.access = ko.observable(!!settingsGet('CoreAccess'));
@ -32,35 +31,25 @@ class AboutAdminSettings
this.coreRemoteVersionHtmlDesc = ko.computed(() => { this.coreRemoteVersionHtmlDesc = ko.computed(() => {
translatorTrigger(); translatorTrigger();
return i18n('TAB_ABOUT/HTML_NEW_VERSION', {'VERSION': this.coreRemoteVersion()}); return i18n('TAB_ABOUT/HTML_NEW_VERSION', { 'VERSION': this.coreRemoteVersion() });
}); });
this.statusType = ko.computed(() => { this.statusType = ko.computed(() => {
let type = ''; let type = '';
const const versionToCompare = this.coreVersionCompare(),
versionToCompare = this.coreVersionCompare(),
isChecking = this.coreChecking(), isChecking = this.coreChecking(),
isUpdating = this.coreUpdating(), isUpdating = this.coreUpdating(),
isReal = this.coreReal(); isReal = this.coreReal();
if (isChecking) if (isChecking) {
{
type = 'checking'; type = 'checking';
} } else if (isUpdating) {
else if (isUpdating)
{
type = 'updating'; type = 'updating';
} } else if (isReal && 0 === versionToCompare) {
else if (isReal && 0 === versionToCompare)
{
type = 'up-to-date'; type = 'up-to-date';
} } else if (isReal && -1 === versionToCompare) {
else if (isReal && -1 === versionToCompare)
{
type = 'available'; type = 'available';
} } else if (!isReal) {
else if (!isReal)
{
type = 'error'; type = 'error';
this.errorDesc('Cannot access the repository at the moment.'); this.errorDesc('Cannot access the repository at the moment.');
} }
@ -70,18 +59,16 @@ class AboutAdminSettings
} }
onBuild() { onBuild() {
if (this.access() && !this.community) if (this.access() && !this.community) {
{
getApp().reloadCoreData(); getApp().reloadCoreData();
} }
} }
updateCoreData() { updateCoreData() {
if (!this.coreUpdating() && !this.community) if (!this.coreUpdating() && !this.community) {
{
getApp().updateCoreData(); getApp().updateCoreData();
} }
} }
} }
export {AboutAdminSettings, AboutAdminSettings as default}; export { AboutAdminSettings, AboutAdminSettings as default };

View file

@ -1,18 +1,16 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {Magics} from 'Common/Enums'; import { Magics } from 'Common/Enums';
import {settingsSaveHelperSimpleFunction, trim} from 'Common/Utils'; import { settingsSaveHelperSimpleFunction, trim } from 'Common/Utils';
import {i18n, trigger as translatorTrigger} from 'Common/Translator'; import { i18n, trigger as translatorTrigger } from 'Common/Translator';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
import AppStore from 'Stores/Admin/App'; import AppStore from 'Stores/Admin/App';
import {settingsGet} from 'Storage/Settings'; import { settingsGet } from 'Storage/Settings';
class BrandingAdminSettings class BrandingAdminSettings {
{
constructor() { constructor() {
this.capa = AppStore.prem; this.capa = AppStore.prem;
@ -33,9 +31,9 @@ class BrandingAdminSettings
this.welcomePageDisplay.options = ko.computed(() => { this.welcomePageDisplay.options = ko.computed(() => {
translatorTrigger(); translatorTrigger();
return [ return [
{optValue: 'none', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_NONE')}, { optValue: 'none', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_NONE') },
{optValue: 'once', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ONCE')}, { optValue: 'once', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ONCE') },
{optValue: 'always', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ALWAYS')} { optValue: 'always', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ALWAYS') }
]; ];
}); });
@ -45,8 +43,7 @@ class BrandingAdminSettings
onBuild() { onBuild() {
_.delay(() => { _.delay(() => {
const const f1 = settingsSaveHelperSimpleFunction(this.title.trigger, this),
f1 = settingsSaveHelperSimpleFunction(this.title.trigger, this),
f2 = settingsSaveHelperSimpleFunction(this.loadingDesc.trigger, this), f2 = settingsSaveHelperSimpleFunction(this.loadingDesc.trigger, this),
f3 = settingsSaveHelperSimpleFunction(this.faviconUrl.trigger, this); f3 = settingsSaveHelperSimpleFunction(this.faviconUrl.trigger, this);
@ -71,4 +68,4 @@ class BrandingAdminSettings
} }
} }
export {BrandingAdminSettings, BrandingAdminSettings as default}; export { BrandingAdminSettings, BrandingAdminSettings as default };

View file

@ -1,32 +1,24 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import { import { settingsSaveHelperSimpleFunction, defautOptionsAfterRender, inArray, trim, boolToAjax } from 'Common/Utils';
settingsSaveHelperSimpleFunction,
defautOptionsAfterRender,
inArray, trim, boolToAjax
} from 'Common/Utils';
import {SaveSettingsStep, StorageResultType, Magics} from 'Common/Enums'; import { SaveSettingsStep, StorageResultType, Magics } from 'Common/Enums';
import {i18n} from 'Common/Translator'; import { i18n } from 'Common/Translator';
import {settingsGet} from 'Storage/Settings'; import { settingsGet } from 'Storage/Settings';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
import {command} from 'Knoin/Knoin'; import { command } from 'Knoin/Knoin';
class ContactsAdminSettings class ContactsAdminSettings {
{
constructor() { constructor() {
this.defautOptionsAfterRender = defautOptionsAfterRender; this.defautOptionsAfterRender = defautOptionsAfterRender;
this.enableContacts = ko.observable(!!settingsGet('ContactsEnable')); this.enableContacts = ko.observable(!!settingsGet('ContactsEnable'));
this.contactsSync = ko.observable(!!settingsGet('ContactsSync')); this.contactsSync = ko.observable(!!settingsGet('ContactsSync'));
const const supportedTypes = [],
supportedTypes = [],
types = ['sqlite', 'mysql', 'pgsql'], types = ['sqlite', 'mysql', 'pgsql'],
getTypeName = (name) => { getTypeName = (name) => {
switch (name) switch (name) {
{
case 'sqlite': case 'sqlite':
name = 'SQLite'; name = 'SQLite';
break; break;
@ -42,16 +34,13 @@ class ContactsAdminSettings
return name; return name;
}; };
if (settingsGet('SQLiteIsSupported')) if (settingsGet('SQLiteIsSupported')) {
{
supportedTypes.push('sqlite'); supportedTypes.push('sqlite');
} }
if (settingsGet('MySqlIsSupported')) if (settingsGet('MySqlIsSupported')) {
{
supportedTypes.push('mysql'); supportedTypes.push('mysql');
} }
if (settingsGet('PostgreSqlIsSupported')) if (settingsGet('PostgreSqlIsSupported')) {
{
supportedTypes.push('pgsql'); supportedTypes.push('pgsql');
} }
@ -70,26 +59,22 @@ class ContactsAdminSettings
this.contactsTypes(types); this.contactsTypes(types);
this.contactsType = ko.observable(''); this.contactsType = ko.observable('');
this.mainContactsType = ko.computed({ this.mainContactsType = ko
read: this.contactsType, .computed({
write: (value) => { read: this.contactsType,
if (value !== this.contactsType()) write: (value) => {
{ if (value !== this.contactsType()) {
if (-1 < inArray(value, supportedTypes)) if (-1 < inArray(value, supportedTypes)) {
{ this.contactsType(value);
this.contactsType(value); } else if (0 < supportedTypes.length) {
} this.contactsType('');
else if (0 < supportedTypes.length) }
{ } else {
this.contactsType(''); this.contactsType.valueHasMutated();
} }
} }
else })
{ .extend({ notify: 'always' });
this.contactsType.valueHasMutated();
}
}
}).extend({notify: 'always'});
this.contactsType.subscribe(() => { this.contactsType.subscribe(() => {
this.testContactsSuccess(false); this.testContactsSuccess(false);
@ -136,19 +121,13 @@ class ContactsAdminSettings
this.testContactsError(false); this.testContactsError(false);
this.testContactsErrorMessage(''); this.testContactsErrorMessage('');
if (StorageResultType.Success === result && data && data.Result && data.Result.Result) if (StorageResultType.Success === result && data && data.Result && data.Result.Result) {
{
this.testContactsSuccess(true); this.testContactsSuccess(true);
} } else {
else
{
this.testContactsError(true); this.testContactsError(true);
if (data && data.Result) if (data && data.Result) {
{
this.testContactsErrorMessage(data.Result.Message || ''); this.testContactsErrorMessage(data.Result.Message || '');
} } else {
else
{
this.testContactsErrorMessage(''); this.testContactsErrorMessage('');
} }
} }
@ -164,8 +143,7 @@ class ContactsAdminSettings
onBuild() { onBuild() {
_.delay(() => { _.delay(() => {
const const f1 = settingsSaveHelperSimpleFunction(this.pdoDsnTrigger, this),
f1 = settingsSaveHelperSimpleFunction(this.pdoDsnTrigger, this),
f3 = settingsSaveHelperSimpleFunction(this.pdoUserTrigger, this), f3 = settingsSaveHelperSimpleFunction(this.pdoUserTrigger, this),
f4 = settingsSaveHelperSimpleFunction(this.pdoPasswordTrigger, this), f4 = settingsSaveHelperSimpleFunction(this.pdoPasswordTrigger, this),
f5 = settingsSaveHelperSimpleFunction(this.contactsTypeTrigger, this); f5 = settingsSaveHelperSimpleFunction(this.contactsTypeTrigger, this);
@ -211,4 +189,4 @@ class ContactsAdminSettings
} }
} }
export {ContactsAdminSettings, ContactsAdminSettings as default}; export { ContactsAdminSettings, ContactsAdminSettings as default };

View file

@ -1,17 +1,15 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {StorageResultType} from 'Common/Enums'; import { StorageResultType } from 'Common/Enums';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
import DomainStore from 'Stores/Admin/Domain'; import DomainStore from 'Stores/Admin/Domain';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
import {getApp} from 'Helper/Apps/Admin'; import { getApp } from 'Helper/Apps/Admin';
class DomainsAdminSettings class DomainsAdminSettings {
{
constructor() { constructor() {
this.domains = DomainStore.domains; this.domains = DomainStore.domains;
@ -43,21 +41,19 @@ class DomainsAdminSettings
onBuild(oDom) { onBuild(oDom) {
const self = this; const self = this;
oDom oDom.on('click', '.b-admin-domains-list-table .e-item .e-action', function() {
.on('click', '.b-admin-domains-list-table .e-item .e-action', function() { // eslint-disable-line prefer-arrow-callback // eslint-disable-line prefer-arrow-callback
const domainItem = ko.dataFor(this); // eslint-disable-line no-invalid-this const domainItem = ko.dataFor(this); // eslint-disable-line no-invalid-this
if (domainItem) if (domainItem) {
{ Remote.domain(self.onDomainLoadRequest, domainItem.name);
Remote.domain(self.onDomainLoadRequest, domainItem.name); }
} });
});
getApp().reloadDomainList(); getApp().reloadDomainList();
} }
onDomainLoadRequest(sResult, oData) { onDomainLoadRequest(sResult, oData) {
if (StorageResultType.Success === sResult && oData && oData.Result) if (StorageResultType.Success === sResult && oData && oData.Result) {
{
showScreenPopup(require('View/Popup/Domain'), [oData.Result]); showScreenPopup(require('View/Popup/Domain'), [oData.Result]);
} }
} }
@ -67,4 +63,4 @@ class DomainsAdminSettings
} }
} }
export {DomainsAdminSettings, DomainsAdminSettings as default}; export { DomainsAdminSettings, DomainsAdminSettings as default };

View file

@ -1,18 +1,22 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import { import {
trim, pInt, boolToAjax, settingsSaveHelperSimpleFunction, trim,
changeTheme, convertThemeName, convertLangName pInt,
boolToAjax,
settingsSaveHelperSimpleFunction,
changeTheme,
convertThemeName,
convertLangName
} from 'Common/Utils'; } from 'Common/Utils';
import {SaveSettingsStep, Magics} from 'Common/Enums'; import { SaveSettingsStep, Magics } from 'Common/Enums';
import {reload as translatorReload} from 'Common/Translator'; import { reload as translatorReload } from 'Common/Translator';
import {phpInfo} from 'Common/Links'; import { phpInfo } from 'Common/Links';
import {settingsGet} from 'Storage/Settings'; import { settingsGet } from 'Storage/Settings';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
@ -21,8 +25,7 @@ import LanguageStore from 'Stores/Language';
import AppAdminStore from 'Stores/Admin/App'; import AppAdminStore from 'Stores/Admin/App';
import CapaAdminStore from 'Stores/Admin/Capa'; import CapaAdminStore from 'Stores/Admin/Capa';
class GeneralAdminSettings class GeneralAdminSettings {
{
constructor() { constructor() {
this.language = LanguageStore.language; this.language = LanguageStore.language;
this.languages = LanguageStore.languages; this.languages = LanguageStore.languages;
@ -46,29 +49,37 @@ class GeneralAdminSettings
this.dataFolderAccess = AppAdminStore.dataFolderAccess; this.dataFolderAccess = AppAdminStore.dataFolderAccess;
this.mainAttachmentLimit = ko.observable(pInt(settingsGet('AttachmentLimit')) / (Magics.BitLength1024 * Magics.BitLength1024)).extend({posInterer: 25}); this.mainAttachmentLimit = ko
.observable(pInt(settingsGet('AttachmentLimit')) / (Magics.BitLength1024 * Magics.BitLength1024))
.extend({ posInterer: 25 });
this.uploadData = settingsGet('PhpUploadSizes'); this.uploadData = settingsGet('PhpUploadSizes');
this.uploadDataDesc = this.uploadData && (this.uploadData.upload_max_filesize || this.uploadData.post_max_size) ? [ this.uploadDataDesc =
this.uploadData.upload_max_filesize ? 'upload_max_filesize = ' + this.uploadData.upload_max_filesize + '; ' : '', this.uploadData && (this.uploadData.upload_max_filesize || this.uploadData.post_max_size)
this.uploadData.post_max_size ? 'post_max_size = ' + this.uploadData.post_max_size : '' ? [
].join('') : ''; this.uploadData.upload_max_filesize
? 'upload_max_filesize = ' + this.uploadData.upload_max_filesize + '; '
: '',
this.uploadData.post_max_size ? 'post_max_size = ' + this.uploadData.post_max_size : ''
].join('')
: '';
this.themesOptions = ko.computed(() => _.map(this.themes(), (theme) => ({optValue: theme, optText: convertThemeName(theme)}))); this.themesOptions = ko.computed(() =>
_.map(this.themes(), (theme) => ({ optValue: theme, optText: convertThemeName(theme) }))
);
this.languageFullName = ko.computed(() => convertLangName(this.language())); this.languageFullName = ko.computed(() => convertLangName(this.language()));
this.languageAdminFullName = ko.computed(() => convertLangName(this.languageAdmin())); this.languageAdminFullName = ko.computed(() => convertLangName(this.languageAdmin()));
this.attachmentLimitTrigger = ko.observable(SaveSettingsStep.Idle); this.attachmentLimitTrigger = ko.observable(SaveSettingsStep.Idle);
this.languageTrigger = ko.observable(SaveSettingsStep.Idle); this.languageTrigger = ko.observable(SaveSettingsStep.Idle);
this.languageAdminTrigger = ko.observable(SaveSettingsStep.Idle).extend({throttle: Magics.Time100ms}); this.languageAdminTrigger = ko.observable(SaveSettingsStep.Idle).extend({ throttle: Magics.Time100ms });
this.themeTrigger = ko.observable(SaveSettingsStep.Idle); this.themeTrigger = ko.observable(SaveSettingsStep.Idle);
} }
onBuild() { onBuild() {
_.delay(() => { _.delay(() => {
const const f1 = settingsSaveHelperSimpleFunction(this.attachmentLimitTrigger, this),
f1 = settingsSaveHelperSimpleFunction(this.attachmentLimitTrigger, this),
f2 = settingsSaveHelperSimpleFunction(this.languageTrigger, this), f2 = settingsSaveHelperSimpleFunction(this.languageTrigger, this),
f3 = settingsSaveHelperSimpleFunction(this.themeTrigger, this), f3 = settingsSaveHelperSimpleFunction(this.themeTrigger, this),
fReloadLanguageHelper = (saveSettingsStep) => () => { fReloadLanguageHelper = (saveSettingsStep) => () => {
@ -90,14 +101,13 @@ class GeneralAdminSettings
this.languageAdmin.subscribe((value) => { this.languageAdmin.subscribe((value) => {
this.languageAdminTrigger(SaveSettingsStep.Animate); this.languageAdminTrigger(SaveSettingsStep.Animate);
translatorReload(true, value).then( translatorReload(true, value)
fReloadLanguageHelper(SaveSettingsStep.TrueResult), .then(fReloadLanguageHelper(SaveSettingsStep.TrueResult), fReloadLanguageHelper(SaveSettingsStep.FalseResult))
fReloadLanguageHelper(SaveSettingsStep.FalseResult) .then(() => {
).then(() => { Remote.saveAdminConfig(null, {
Remote.saveAdminConfig(null, { 'LanguageAdmin': trim(value)
'LanguageAdmin': trim(value) });
}); });
});
}); });
this.theme.subscribe((value) => { this.theme.subscribe((value) => {
@ -164,14 +174,14 @@ class GeneralAdminSettings
} }
selectLanguage() { selectLanguage() {
showScreenPopup(require('View/Popup/Languages'), [ showScreenPopup(require('View/Popup/Languages'), [this.language, this.languages(), LanguageStore.userLanguage()]);
this.language, this.languages(), LanguageStore.userLanguage()
]);
} }
selectLanguageAdmin() { selectLanguageAdmin() {
showScreenPopup(require('View/Popup/Languages'), [ showScreenPopup(require('View/Popup/Languages'), [
this.languageAdmin, this.languagesAdmin(), LanguageStore.userLanguageAdmin() this.languageAdmin,
this.languagesAdmin(),
LanguageStore.userLanguageAdmin()
]); ]);
} }
@ -183,4 +193,4 @@ class GeneralAdminSettings
} }
} }
export {GeneralAdminSettings, GeneralAdminSettings as default}; export { GeneralAdminSettings, GeneralAdminSettings as default };

View file

@ -1,16 +1,14 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {settingsSaveHelperSimpleFunction, boolToAjax, trim} from 'Common/Utils'; import { settingsSaveHelperSimpleFunction, boolToAjax, trim } from 'Common/Utils';
import {settingsGet} from 'Storage/Settings'; import { settingsGet } from 'Storage/Settings';
import AppStore from 'Stores/Admin/App'; import AppStore from 'Stores/Admin/App';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
class LoginAdminSettings class LoginAdminSettings {
{
constructor() { constructor() {
this.determineUserLanguage = AppStore.determineUserLanguage; this.determineUserLanguage = AppStore.determineUserLanguage;
this.determineUserDomain = AppStore.determineUserDomain; this.determineUserDomain = AppStore.determineUserDomain;
@ -52,4 +50,4 @@ class LoginAdminSettings
} }
} }
export {LoginAdminSettings, LoginAdminSettings as default}; export { LoginAdminSettings, LoginAdminSettings as default };

View file

@ -1,18 +1,16 @@
import window from 'window'; import window from 'window';
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {StorageResultType, Notification} from 'Common/Enums'; import { StorageResultType, Notification } from 'Common/Enums';
import {getNotification} from 'Common/Translator'; import { getNotification } from 'Common/Translator';
import PackageStore from 'Stores/Admin/Package'; import PackageStore from 'Stores/Admin/Package';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
import {getApp} from 'Helper/Apps/Admin'; import { getApp } from 'Helper/Apps/Admin';
class PackagesAdminSettings class PackagesAdminSettings {
{
constructor() { constructor() {
this.packagesError = ko.observable(''); this.packagesError = ko.observable('');
@ -37,54 +35,44 @@ class PackagesAdminSettings
requestHelper(packageToRequest, install) { requestHelper(packageToRequest, install) {
return (result, data) => { return (result, data) => {
if (StorageResultType.Success !== result || !data || !data.Result) {
if (StorageResultType.Success !== result || !data || !data.Result) if (data && data.ErrorCode) {
{
if (data && data.ErrorCode)
{
this.packagesError(getNotification(data.ErrorCode)); this.packagesError(getNotification(data.ErrorCode));
} } else {
else this.packagesError(
{ getNotification(install ? Notification.CantInstallPackage : Notification.CantDeletePackage)
this.packagesError(getNotification( );
install ? Notification.CantInstallPackage : Notification.CantDeletePackage));
} }
} }
_.each(this.packages(), (item) => { _.each(this.packages(), (item) => {
if (item && packageToRequest && item.loading && item.loading() && packageToRequest.file === item.file) if (item && packageToRequest && item.loading && item.loading() && packageToRequest.file === item.file) {
{
packageToRequest.loading(false); packageToRequest.loading(false);
item.loading(false); item.loading(false);
} }
}); });
if (StorageResultType.Success === result && data && data.Result && data.Result.Reload) if (StorageResultType.Success === result && data && data.Result && data.Result.Reload) {
{
window.location.reload(); window.location.reload();
} } else {
else
{
getApp().reloadPackagesList(); getApp().reloadPackagesList();
} }
}; };
} }
deletePackage(packageToDelete) { deletePackage(packageToDelete) {
if (packageToDelete) if (packageToDelete) {
{
packageToDelete.loading(true); packageToDelete.loading(true);
Remote.packageDelete(this.requestHelper(packageToDelete, false), packageToDelete); Remote.packageDelete(this.requestHelper(packageToDelete, false), packageToDelete);
} }
} }
installPackage(packageToInstall) { installPackage(packageToInstall) {
if (packageToInstall) if (packageToInstall) {
{
packageToInstall.loading(true); packageToInstall.loading(true);
Remote.packageInstall(this.requestHelper(packageToInstall, true), packageToInstall); Remote.packageInstall(this.requestHelper(packageToInstall, true), packageToInstall);
} }
} }
} }
export {PackagesAdminSettings, PackagesAdminSettings as default}; export { PackagesAdminSettings, PackagesAdminSettings as default };

View file

@ -1,22 +1,21 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {StorageResultType, Notification} from 'Common/Enums'; import { StorageResultType, Notification } from 'Common/Enums';
import {getNotification} from 'Common/Translator'; import { getNotification } from 'Common/Translator';
import {boolToAjax} from 'Common/Utils'; import { boolToAjax } from 'Common/Utils';
import {settingsGet} from 'Storage/Settings'; import { settingsGet } from 'Storage/Settings';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
import AppStore from 'Stores/Admin/App'; import AppStore from 'Stores/Admin/App';
import PluginStore from 'Stores/Admin/Plugin'; import PluginStore from 'Stores/Admin/Plugin';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
import {getApp} from 'Helper/Apps/Admin'; import { getApp } from 'Helper/Apps/Admin';
class PluginsAdminSettings class PluginsAdminSettings {
{
constructor() { constructor() {
this.enabledPlugins = ko.observable(!!settingsGet('EnabledPlugins')); this.enabledPlugins = ko.observable(!!settingsGet('EnabledPlugins'));
@ -41,21 +40,20 @@ class PluginsAdminSettings
} }
onBuild(oDom) { onBuild(oDom) {
const self = this; const self = this;
oDom oDom
.on('click', '.e-item .configure-plugin-action', function() { // eslint-disable-line prefer-arrow-callback .on('click', '.e-item .configure-plugin-action', function() {
// eslint-disable-line prefer-arrow-callback
const plugin = ko.dataFor(this); // eslint-disable-line no-invalid-this const plugin = ko.dataFor(this); // eslint-disable-line no-invalid-this
if (plugin) if (plugin) {
{
self.configurePlugin(plugin); self.configurePlugin(plugin);
} }
}) })
.on('click', '.e-item .disabled-plugin', function() { // eslint-disable-line prefer-arrow-callback .on('click', '.e-item .disabled-plugin', function() {
// eslint-disable-line prefer-arrow-callback
const plugin = ko.dataFor(this); // eslint-disable-line no-invalid-this const plugin = ko.dataFor(this); // eslint-disable-line no-invalid-this
if (plugin) if (plugin) {
{
self.disablePlugin(plugin); self.disablePlugin(plugin);
} }
}); });
@ -73,23 +71,17 @@ class PluginsAdminSettings
} }
onPluginLoadRequest(result, data) { onPluginLoadRequest(result, data) {
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{
showScreenPopup(require('View/Popup/Plugin'), [data.Result]); showScreenPopup(require('View/Popup/Plugin'), [data.Result]);
} }
} }
onPluginDisableRequest(result, data) { onPluginDisableRequest(result, data) {
if (StorageResultType.Success === result && data) if (StorageResultType.Success === result && data) {
{ if (!data.Result && data.ErrorCode) {
if (!data.Result && data.ErrorCode) if (Notification.UnsupportedPluginPackage === data.ErrorCode && data.ErrorMessage && '' !== data.ErrorMessage) {
{
if (Notification.UnsupportedPluginPackage === data.ErrorCode && data.ErrorMessage && '' !== data.ErrorMessage)
{
PluginStore.plugins.error(data.ErrorMessage); PluginStore.plugins.error(data.ErrorMessage);
} } else {
else
{
PluginStore.plugins.error(getNotification(data.ErrorCode)); PluginStore.plugins.error(getNotification(data.ErrorCode));
} }
} }
@ -99,4 +91,4 @@ class PluginsAdminSettings
} }
} }
export {PluginsAdminSettings, PluginsAdminSettings as default}; export { PluginsAdminSettings, PluginsAdminSettings as default };

View file

@ -1,23 +1,18 @@
import _ from '_'; import _ from '_';
import {settingsSaveHelperSimpleFunction, trim, boolToAjax} from 'Common/Utils'; import { settingsSaveHelperSimpleFunction, trim, boolToAjax } from 'Common/Utils';
import {Magics} from 'Common/Enums'; import { Magics } from 'Common/Enums';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
import {BrandingAdminSettings} from 'Settings/Admin/Branding'; import { BrandingAdminSettings } from 'Settings/Admin/Branding';
class BrandingPremAdminSettings extends BrandingAdminSettings class BrandingPremAdminSettings extends BrandingAdminSettings {
{
onBuild(dom) { onBuild(dom) {
super.onBuild(dom); super.onBuild(dom);
if (this.capa && this.capa() && !this.community) if (this.capa && this.capa() && !this.community) {
{
_.delay(() => { _.delay(() => {
const f1 = settingsSaveHelperSimpleFunction(this.loginLogo.trigger, this),
const
f1 = settingsSaveHelperSimpleFunction(this.loginLogo.trigger, this),
f2 = settingsSaveHelperSimpleFunction(this.loginDescription.trigger, this), f2 = settingsSaveHelperSimpleFunction(this.loginDescription.trigger, this),
f3 = settingsSaveHelperSimpleFunction(this.loginCss.trigger, this), f3 = settingsSaveHelperSimpleFunction(this.loginCss.trigger, this),
f4 = settingsSaveHelperSimpleFunction(this.userLogo.trigger, this), f4 = settingsSaveHelperSimpleFunction(this.userLogo.trigger, this),
@ -100,10 +95,9 @@ class BrandingPremAdminSettings extends BrandingAdminSettings
'LoginPowered': boolToAjax(value) 'LoginPowered': boolToAjax(value)
}); });
}); });
}, Magics.Time50ms); }, Magics.Time50ms);
} }
} }
} }
export {BrandingPremAdminSettings, BrandingPremAdminSettings as default}; export { BrandingPremAdminSettings, BrandingPremAdminSettings as default };

View file

@ -1,16 +1,14 @@
import ko from 'ko'; import ko from 'ko';
import moment from 'moment'; import moment from 'moment';
import {settingsGet} from 'Storage/Settings'; import { settingsGet } from 'Storage/Settings';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
import LicenseStore from 'Stores/Admin/License'; import LicenseStore from 'Stores/Admin/License';
import {getApp} from 'Helper/Apps/Admin'; import { getApp } from 'Helper/Apps/Admin';
class LicensingPremAdminSettings class LicensingPremAdminSettings {
{
constructor() { constructor() {
this.licensing = LicenseStore.licensing; this.licensing = LicenseStore.licensing;
this.licensingProcess = LicenseStore.licensingProcess; this.licensingProcess = LicenseStore.licensingProcess;
@ -23,16 +21,14 @@ class LicensingPremAdminSettings
this.subscriptionEnabled = ko.observable(!!settingsGet('SubscriptionEnabled')); this.subscriptionEnabled = ko.observable(!!settingsGet('SubscriptionEnabled'));
this.licenseTrigger.subscribe(() => { this.licenseTrigger.subscribe(() => {
if (this.subscriptionEnabled()) if (this.subscriptionEnabled()) {
{
getApp().reloadLicensing(true); getApp().reloadLicensing(true);
} }
}); });
} }
onBuild() { onBuild() {
if (this.subscriptionEnabled()) if (this.subscriptionEnabled()) {
{
getApp().reloadLicensing(false); getApp().reloadLicensing(false);
} }
} }
@ -60,12 +56,11 @@ class LicensingPremAdminSettings
* @returns {string} * @returns {string}
*/ */
licenseExpiredMomentValue() { licenseExpiredMomentValue() {
const const time = this.licenseExpired(),
time = this.licenseExpired(),
momentUnix = moment.unix(time); momentUnix = moment.unix(time);
return this.licenseIsUnlim() ? 'Never' : (time && (momentUnix.format('LL') + ' (' + momentUnix.from(moment()) + ')')); return this.licenseIsUnlim() ? 'Never' : time && momentUnix.format('LL') + ' (' + momentUnix.from(moment()) + ')';
} }
} }
export {LicensingPremAdminSettings, LicensingPremAdminSettings as default}; export { LicensingPremAdminSettings, LicensingPremAdminSettings as default };

View file

@ -1,22 +1,20 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {trim, boolToAjax} from 'Common/Utils'; import { trim, boolToAjax } from 'Common/Utils';
import {phpInfo} from 'Common/Links'; import { phpInfo } from 'Common/Links';
import {StorageResultType, Magics} from 'Common/Enums'; import { StorageResultType, Magics } from 'Common/Enums';
import {settingsGet} from 'Storage/Settings'; import { settingsGet } from 'Storage/Settings';
import AppAdminStore from 'Stores/Admin/App'; import AppAdminStore from 'Stores/Admin/App';
import CapaAdminStore from 'Stores/Admin/Capa'; import CapaAdminStore from 'Stores/Admin/Capa';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
import {command} from 'Knoin/Knoin'; import { command } from 'Knoin/Knoin';
class SecurityAdminSettings class SecurityAdminSettings {
{
constructor() { constructor() {
this.useLocalProxyForExternalImages = AppAdminStore.useLocalProxyForExternalImages; this.useLocalProxyForExternalImages = AppAdminStore.useLocalProxyForExternalImages;
@ -28,8 +26,7 @@ class SecurityAdminSettings
this.capaTwoFactorAuthForce = CapaAdminStore.twoFactorAuthForce; this.capaTwoFactorAuthForce = CapaAdminStore.twoFactorAuthForce;
this.capaTwoFactorAuth.subscribe((value) => { this.capaTwoFactorAuth.subscribe((value) => {
if (!value) if (!value) {
{
this.capaTwoFactorAuthForce(false); this.capaTwoFactorAuthForce(false);
} }
}); });
@ -38,8 +35,7 @@ class SecurityAdminSettings
this.allowSelfSigned = ko.observable(!!settingsGet('AllowSelfSigned')); this.allowSelfSigned = ko.observable(!!settingsGet('AllowSelfSigned'));
this.verifySslCertificate.subscribe((value) => { this.verifySslCertificate.subscribe((value) => {
if (!value) if (!value) {
{
this.allowSelfSigned(true); this.allowSelfSigned(true);
} }
}); });
@ -84,15 +80,12 @@ class SecurityAdminSettings
@command((self) => '' !== trim(self.adminLogin()) && '' !== self.adminPassword()) @command((self) => '' !== trim(self.adminLogin()) && '' !== self.adminPassword())
saveNewAdminPasswordCommand() { saveNewAdminPasswordCommand() {
if ('' === trim(this.adminLogin())) {
if ('' === trim(this.adminLogin()))
{
this.adminLoginError(true); this.adminLoginError(true);
return false; return false;
} }
if (this.adminPasswordNew() !== this.adminPasswordNew2()) if (this.adminPasswordNew() !== this.adminPasswordNew2()) {
{
this.adminPasswordNewError(true); this.adminPasswordNewError(true);
return false; return false;
} }
@ -119,8 +112,7 @@ class SecurityAdminSettings
} }
onNewAdminPasswordResponse(result, data) { onNewAdminPasswordResponse(result, data) {
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{
this.adminPassword(''); this.adminPassword('');
this.adminPasswordNew(''); this.adminPasswordNew('');
this.adminPasswordNew2(''); this.adminPasswordNew2('');
@ -128,9 +120,7 @@ class SecurityAdminSettings
this.adminPasswordUpdateSuccess(true); this.adminPasswordUpdateSuccess(true);
this.weakPassword(!!data.Result.Weak); this.weakPassword(!!data.Result.Weak);
} } else {
else
{
this.adminPasswordUpdateError(true); this.adminPasswordUpdateError(true);
} }
} }
@ -191,4 +181,4 @@ class SecurityAdminSettings
} }
} }
export {SecurityAdminSettings, SecurityAdminSettings as default}; export { SecurityAdminSettings, SecurityAdminSettings as default };

View file

@ -1,16 +1,14 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {SaveSettingsStep, Magics} from 'Common/Enums'; import { SaveSettingsStep, Magics } from 'Common/Enums';
import {settingsSaveHelperSimpleFunction, trim, boolToAjax} from 'Common/Utils'; import { settingsSaveHelperSimpleFunction, trim, boolToAjax } from 'Common/Utils';
import SocialStore from 'Stores/Social'; import SocialStore from 'Stores/Social';
import Remote from 'Remote/Admin/Ajax'; import Remote from 'Remote/Admin/Ajax';
class SocialAdminSettings class SocialAdminSettings {
{
constructor() { constructor() {
this.googleEnable = SocialStore.google.enabled; this.googleEnable = SocialStore.google.enabled;
this.googleEnableAuth = SocialStore.google.capa.auth; this.googleEnableAuth = SocialStore.google.capa.auth;
@ -52,8 +50,7 @@ class SocialAdminSettings
onBuild() { onBuild() {
_.delay(() => { _.delay(() => {
const const f1 = settingsSaveHelperSimpleFunction(this.facebookTrigger1, this),
f1 = settingsSaveHelperSimpleFunction(this.facebookTrigger1, this),
f2 = settingsSaveHelperSimpleFunction(this.facebookTrigger2, this), f2 = settingsSaveHelperSimpleFunction(this.facebookTrigger2, this),
f3 = settingsSaveHelperSimpleFunction(this.twitterTrigger1, this), f3 = settingsSaveHelperSimpleFunction(this.twitterTrigger1, this),
f4 = settingsSaveHelperSimpleFunction(this.twitterTrigger2, this), f4 = settingsSaveHelperSimpleFunction(this.twitterTrigger2, this),
@ -63,8 +60,7 @@ class SocialAdminSettings
f8 = settingsSaveHelperSimpleFunction(this.dropboxTrigger1, this); f8 = settingsSaveHelperSimpleFunction(this.dropboxTrigger1, this);
this.facebookEnable.subscribe((value) => { this.facebookEnable.subscribe((value) => {
if (this.facebookSupported()) if (this.facebookSupported()) {
{
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'FacebookEnable': boolToAjax(value) 'FacebookEnable': boolToAjax(value)
}); });
@ -72,8 +68,7 @@ class SocialAdminSettings
}); });
this.facebookAppID.subscribe((value) => { this.facebookAppID.subscribe((value) => {
if (this.facebookSupported()) if (this.facebookSupported()) {
{
Remote.saveAdminConfig(f1, { Remote.saveAdminConfig(f1, {
'FacebookAppID': trim(value) 'FacebookAppID': trim(value)
}); });
@ -81,8 +76,7 @@ class SocialAdminSettings
}); });
this.facebookAppSecret.subscribe((value) => { this.facebookAppSecret.subscribe((value) => {
if (this.facebookSupported()) if (this.facebookSupported()) {
{
Remote.saveAdminConfig(f2, { Remote.saveAdminConfig(f2, {
'FacebookAppSecret': trim(value) 'FacebookAppSecret': trim(value)
}); });
@ -107,4 +101,4 @@ class SocialAdminSettings
} }
} }
export {SocialAdminSettings, SocialAdminSettings as default}; export { SocialAdminSettings, SocialAdminSettings as default };

View file

@ -1,23 +1,21 @@
import window from 'window'; import window from 'window';
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {Capa, StorageResultType} from 'Common/Enums'; import { Capa, StorageResultType } from 'Common/Enums';
import {root} from 'Common/Links'; import { root } from 'Common/Links';
import {capa} from 'Storage/Settings'; import { capa } from 'Storage/Settings';
import AccountStore from 'Stores/User/Account'; import AccountStore from 'Stores/User/Account';
import IdentityStore from 'Stores/User/Identity'; import IdentityStore from 'Stores/User/Identity';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
import {showScreenPopup, routeOff, setHash} from 'Knoin/Knoin'; import { showScreenPopup, routeOff, setHash } from 'Knoin/Knoin';
class AccountsUserSettings class AccountsUserSettings {
{
constructor() { constructor() {
this.allowAdditionalAccount = capa(Capa.AdditionalAccounts); this.allowAdditionalAccount = capa(Capa.AdditionalAccounts);
this.allowIdentities = capa(Capa.Identities); this.allowIdentities = capa(Capa.Identities);
@ -42,8 +40,7 @@ class AccountsUserSettings
} }
editAccount(account) { editAccount(account) {
if (account && account.canBeEdit()) if (account && account.canBeEdit()) {
{
showScreenPopup(require('View/Popup/Account'), [account]); showScreenPopup(require('View/Popup/Account'), [account]);
} }
} }
@ -61,28 +58,21 @@ class AccountsUserSettings
* @returns {void} * @returns {void}
*/ */
deleteAccount(accountToRemove) { deleteAccount(accountToRemove) {
if (accountToRemove && accountToRemove.deleteAccess()) if (accountToRemove && accountToRemove.deleteAccess()) {
{
this.accountForDeletion(null); this.accountForDeletion(null);
if (accountToRemove) if (accountToRemove) {
{
this.accounts.remove((account) => accountToRemove === account); this.accounts.remove((account) => accountToRemove === account);
Remote.accountDelete((result, data) => { Remote.accountDelete((result, data) => {
if (StorageResultType.Success === result && data && data.Result && data.Reload) {
if (StorageResultType.Success === result && data && data.Result && data.Reload)
{
routeOff(); routeOff();
setHash(root(), true); setHash(root(), true);
routeOff(); routeOff();
_.defer(() => window.location.reload()); _.defer(() => window.location.reload());
} } else {
else
{
getApp().accountsAndIdentities(); getApp().accountsAndIdentities();
} }
}, accountToRemove.email); }, accountToRemove.email);
} }
} }
@ -93,12 +83,10 @@ class AccountsUserSettings
* @returns {void} * @returns {void}
*/ */
deleteIdentity(identityToRemove) { deleteIdentity(identityToRemove) {
if (identityToRemove && identityToRemove.deleteAccess()) if (identityToRemove && identityToRemove.deleteAccess()) {
{
this.identityForDeletion(null); this.identityForDeletion(null);
if (identityToRemove) if (identityToRemove) {
{
IdentityStore.identities.remove((oIdentity) => identityToRemove === oIdentity); IdentityStore.identities.remove((oIdentity) => identityToRemove === oIdentity);
Remote.identityDelete(() => { Remote.identityDelete(() => {
@ -109,30 +97,28 @@ class AccountsUserSettings
} }
accountsAndIdentitiesAfterMove() { accountsAndIdentitiesAfterMove() {
Remote.accountsAndIdentitiesSortOrder(null, Remote.accountsAndIdentitiesSortOrder(null, AccountStore.accountsEmails.peek(), IdentityStore.identitiesIDS.peek());
AccountStore.accountsEmails.peek(), IdentityStore.identitiesIDS.peek());
} }
onBuild(oDom) { onBuild(oDom) {
const self = this; const self = this;
oDom oDom
.on('click', '.accounts-list .account-item .e-action', function() { // eslint-disable-line prefer-arrow-callback .on('click', '.accounts-list .account-item .e-action', function() {
// eslint-disable-line prefer-arrow-callback
const account = ko.dataFor(this); // eslint-disable-line no-invalid-this const account = ko.dataFor(this); // eslint-disable-line no-invalid-this
if (account) if (account) {
{
self.editAccount(account); self.editAccount(account);
} }
}) })
.on('click', '.identities-list .identity-item .e-action', function() { // eslint-disable-line prefer-arrow-callback .on('click', '.identities-list .identity-item .e-action', function() {
// eslint-disable-line prefer-arrow-callback
const identity = ko.dataFor(this); // eslint-disable-line no-invalid-this const identity = ko.dataFor(this); // eslint-disable-line no-invalid-this
if (identity) if (identity) {
{
self.editIdentity(identity); self.editIdentity(identity);
} }
}); });
} }
} }
export {AccountsUserSettings, AccountsUserSettings as default}; export { AccountsUserSettings, AccountsUserSettings as default };

View file

@ -1,17 +1,15 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {StorageResultType, Notification} from 'Common/Enums'; import { StorageResultType, Notification } from 'Common/Enums';
import {getNotificationFromResponse, i18n} from 'Common/Translator'; import { getNotificationFromResponse, i18n } from 'Common/Translator';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
import {command} from 'Knoin/Knoin'; import { command } from 'Knoin/Knoin';
class ChangePasswordUserSettings class ChangePasswordUserSettings {
{
constructor() { constructor() {
this.changeProcess = ko.observable(false); this.changeProcess = ko.observable(false);
@ -46,15 +44,15 @@ class ChangePasswordUserSettings
this.onChangePasswordResponse = _.bind(this.onChangePasswordResponse, this); this.onChangePasswordResponse = _.bind(this.onChangePasswordResponse, this);
} }
@command((self) => !self.changeProcess() && '' !== self.currentPassword() && '' !== self.newPassword() && '' !== self.newPassword2()) @command(
(self) =>
!self.changeProcess() && '' !== self.currentPassword() && '' !== self.newPassword() && '' !== self.newPassword2()
)
saveNewPasswordCommand() { saveNewPasswordCommand() {
if (this.newPassword() !== this.newPassword2()) if (this.newPassword() !== this.newPassword2()) {
{
this.passwordMismatch(true); this.passwordMismatch(true);
this.errorDescription(i18n('SETTINGS_CHANGE_PASSWORD/ERROR_PASSWORD_MISMATCH')); this.errorDescription(i18n('SETTINGS_CHANGE_PASSWORD/ERROR_PASSWORD_MISMATCH'));
} } else {
else
{
this.changeProcess(true); this.changeProcess(true);
this.passwordUpdateError(false); this.passwordUpdateError(false);
@ -83,8 +81,7 @@ class ChangePasswordUserSettings
this.errorDescription(''); this.errorDescription('');
this.currentPassword.error(false); this.currentPassword.error(false);
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{
this.currentPassword(''); this.currentPassword('');
this.newPassword(''); this.newPassword('');
this.newPassword2(''); this.newPassword2('');
@ -93,11 +90,8 @@ class ChangePasswordUserSettings
this.currentPassword.error(false); this.currentPassword.error(false);
getApp().setClientSideToken(data.Result); getApp().setClientSideToken(data.Result);
} } else {
else if (data && Notification.CurrentPasswordIncorrect === data.ErrorCode) {
{
if (data && Notification.CurrentPasswordIncorrect === data.ErrorCode)
{
this.currentPassword.error(true); this.currentPassword.error(true);
} }
@ -107,4 +101,4 @@ class ChangePasswordUserSettings
} }
} }
export {ChangePasswordUserSettings, ChangePasswordUserSettings as default}; export { ChangePasswordUserSettings, ChangePasswordUserSettings as default };

View file

@ -1,15 +1,13 @@
import ko from 'ko'; import ko from 'ko';
import {Magics} from 'Common/Enums'; import { Magics } from 'Common/Enums';
import {boolToAjax} from 'Common/Utils'; import { boolToAjax } from 'Common/Utils';
import AppStore from 'Stores/User/App'; import AppStore from 'Stores/User/App';
import ContactStore from 'Stores/User/Contact'; import ContactStore from 'Stores/User/Contact';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
class ContactsUserSettings class ContactsUserSettings {
{
constructor() { constructor() {
this.contactsAutosave = AppStore.contactsAutosave; this.contactsAutosave = AppStore.contactsAutosave;
@ -19,12 +17,16 @@ class ContactsUserSettings
this.contactsSyncUser = ContactStore.contactsSyncUser; this.contactsSyncUser = ContactStore.contactsSyncUser;
this.contactsSyncPass = ContactStore.contactsSyncPass; this.contactsSyncPass = ContactStore.contactsSyncPass;
this.saveTrigger = ko.computed(() => [ this.saveTrigger = ko
this.enableContactsSync() ? '1' : '0', .computed(() =>
this.contactsSyncUrl(), [
this.contactsSyncUser(), this.enableContactsSync() ? '1' : '0',
this.contactsSyncPass() this.contactsSyncUrl(),
].join('|')).extend({throttle: Magics.Time500ms}); this.contactsSyncUser(),
this.contactsSyncPass()
].join('|')
)
.extend({ throttle: Magics.Time500ms });
} }
onBuild() { onBuild() {
@ -35,7 +37,8 @@ class ContactsUserSettings
}); });
this.saveTrigger.subscribe(() => { this.saveTrigger.subscribe(() => {
Remote.saveContactsSyncData(null, Remote.saveContactsSyncData(
null,
this.enableContactsSync(), this.enableContactsSync(),
this.contactsSyncUrl(), this.contactsSyncUrl(),
this.contactsSyncUser(), this.contactsSyncUser(),
@ -45,4 +48,4 @@ class ContactsUserSettings
} }
} }
export {ContactsUserSettings, ContactsUserSettings as default}; export { ContactsUserSettings, ContactsUserSettings as default };

View file

@ -1,20 +1,18 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {windowResizeCallback, isArray, trim, delegateRunOnDestroy} from 'Common/Utils'; import { windowResizeCallback, isArray, trim, delegateRunOnDestroy } from 'Common/Utils';
import {StorageResultType, Notification} from 'Common/Enums'; import { StorageResultType, Notification } from 'Common/Enums';
import {getNotification} from 'Common/Translator'; import { getNotification } from 'Common/Translator';
import FilterStore from 'Stores/User/Filter'; import FilterStore from 'Stores/User/Filter';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
import {FilterModel} from 'Model/Filter'; import { FilterModel } from 'Model/Filter';
import {showScreenPopup, command} from 'Knoin/Knoin'; import { showScreenPopup, command } from 'Knoin/Knoin';
class FiltersUserSettings class FiltersUserSettings {
{
constructor() { constructor() {
this.modules = FilterStore.modules; this.modules = FilterStore.modules;
this.filters = FilterStore.filters; this.filters = FilterStore.filters;
@ -29,8 +27,7 @@ class FiltersUserSettings
this.filters.subscribe(windowResizeCallback); this.filters.subscribe(windowResizeCallback);
this.serverError.subscribe((value) => { this.serverError.subscribe((value) => {
if (!value) if (!value) {
{
this.serverErrorDesc(''); this.serverErrorDesc('');
} }
}, this); }, this);
@ -64,10 +61,8 @@ class FiltersUserSettings
@command((self) => self.haveChanges()) @command((self) => self.haveChanges())
saveChangesCommand() { saveChangesCommand() {
if (!this.filters.saving()) if (!this.filters.saving()) {
{ if (this.filterRaw.active() && '' === trim(this.filterRaw())) {
if (this.filterRaw.active() && '' === trim(this.filterRaw()))
{
this.filterRaw.error(true); this.filterRaw.error(true);
return false; return false;
} }
@ -75,24 +70,23 @@ class FiltersUserSettings
this.filters.saving(true); this.filters.saving(true);
this.saveErrorText(''); this.saveErrorText('');
Remote.filtersSave((result, data) => { Remote.filtersSave(
this.filters.saving(false); (result, data) => {
this.filters.saving(false);
if (StorageResultType.Success === result && data && data.Result) if (StorageResultType.Success === result && data && data.Result) {
{ this.haveChanges(false);
this.haveChanges(false); this.updateList();
this.updateList(); } else if (data && data.ErrorCode) {
} this.saveErrorText(data.ErrorMessageAdditional || getNotification(data.ErrorCode));
else if (data && data.ErrorCode) } else {
{ this.saveErrorText(getNotification(Notification.CantSaveFilters));
this.saveErrorText(data.ErrorMessageAdditional || getNotification(data.ErrorCode)); }
} },
else this.filters(),
{ this.filterRaw(),
this.saveErrorText(getNotification(Notification.CantSaveFilters)); this.filterRaw.active()
} );
}, this.filters(), this.filterRaw(), this.filterRaw.active());
} }
return true; return true;
@ -107,24 +101,25 @@ class FiltersUserSettings
} }
updateList() { updateList() {
if (!this.filters.loading()) if (!this.filters.loading()) {
{
this.filters.loading(true); this.filters.loading(true);
Remote.filtersGet((result, data) => { Remote.filtersGet((result, data) => {
this.filters.loading(false); this.filters.loading(false);
this.serverError(false); this.serverError(false);
if (StorageResultType.Success === result && data && data.Result && isArray(data.Result.Filters)) if (StorageResultType.Success === result && data && data.Result && isArray(data.Result.Filters)) {
{
this.inited(true); this.inited(true);
this.serverError(false); this.serverError(false);
this.filters(_.compact(_.map(data.Result.Filters, (aItem) => { this.filters(
const filter = new FilterModel(); _.compact(
return (filter && filter.parse(aItem)) ? filter : null; _.map(data.Result.Filters, (aItem) => {
}))); const filter = new FilterModel();
return filter && filter.parse(aItem) ? filter : null;
})
)
);
this.modules(data.Result.Modules ? data.Result.Modules : {}); this.modules(data.Result.Modules ? data.Result.Modules : {});
@ -132,16 +127,16 @@ class FiltersUserSettings
this.filterRaw.capa(isArray(data.Result.Capa) ? data.Result.Capa.join(' ') : ''); this.filterRaw.capa(isArray(data.Result.Capa) ? data.Result.Capa.join(' ') : '');
this.filterRaw.active(!!data.Result.RawIsActive); this.filterRaw.active(!!data.Result.RawIsActive);
this.filterRaw.allow(!!data.Result.RawIsAllow); this.filterRaw.allow(!!data.Result.RawIsAllow);
} } else {
else
{
this.filters([]); this.filters([]);
this.modules({}); this.modules({});
this.filterRaw(''); this.filterRaw('');
this.filterRaw.capa({}); this.filterRaw.capa({});
this.serverError(true); this.serverError(true);
this.serverErrorDesc(data && data.ErrorCode ? getNotification(data.ErrorCode) : getNotification(Notification.CantGetFilters)); this.serverErrorDesc(
data && data.ErrorCode ? getNotification(data.ErrorCode) : getNotification(Notification.CantGetFilters)
);
} }
this.haveChanges(false); this.haveChanges(false);
@ -158,43 +153,47 @@ class FiltersUserSettings
const filter = new FilterModel(); const filter = new FilterModel();
filter.generateID(); filter.generateID();
showScreenPopup(require('View/Popup/Filter'), [filter, () => { showScreenPopup(require('View/Popup/Filter'), [
this.filters.push(filter); filter,
this.filterRaw.active(false); () => {
}, false]); this.filters.push(filter);
this.filterRaw.active(false);
},
false
]);
} }
editFilter(filter) { editFilter(filter) {
const clonedFilter = filter.cloneSelf(); const clonedFilter = filter.cloneSelf();
showScreenPopup(require('View/Popup/Filter'), [clonedFilter, () => { showScreenPopup(require('View/Popup/Filter'), [
const clonedFilter,
filters = this.filters(), () => {
index = filters.indexOf(filter); const filters = this.filters(),
index = filters.indexOf(filter);
if (-1 < index && filters[index]) if (-1 < index && filters[index]) {
{ delegateRunOnDestroy(filters[index]);
delegateRunOnDestroy(filters[index]); filters[index] = clonedFilter;
filters[index] = clonedFilter;
this.filters(filters); this.filters(filters);
this.haveChanges(true); this.haveChanges(true);
} }
}, true]); },
true
]);
} }
onBuild(oDom) { onBuild(oDom) {
const self = this; const self = this;
oDom oDom.on('click', '.filter-item .e-action', function() {
.on('click', '.filter-item .e-action', function() { // eslint-disable-line prefer-arrow-callback // eslint-disable-line prefer-arrow-callback
const filter = ko.dataFor(this); // eslint-disable-line no-invalid-this const filter = ko.dataFor(this); // eslint-disable-line no-invalid-this
if (filter) if (filter) {
{ self.editFilter(filter);
self.editFilter(filter); }
} });
});
} }
onShow() { onShow() {
@ -202,4 +201,4 @@ class FiltersUserSettings
} }
} }
export {FiltersUserSettings, FiltersUserSettings as default}; export { FiltersUserSettings, FiltersUserSettings as default };

View file

@ -1,13 +1,12 @@
import ko from 'ko'; import ko from 'ko';
import {ClientSideKeyName, Notification, Magics} from 'Common/Enums'; import { ClientSideKeyName, Notification, Magics } from 'Common/Enums';
import {trim, noop} from 'Common/Utils'; import { trim, noop } from 'Common/Utils';
import {getNotification, i18n} from 'Common/Translator'; import { getNotification, i18n } from 'Common/Translator';
import {removeFolderFromCacheList} from 'Common/Cache'; import { removeFolderFromCacheList } from 'Common/Cache';
import {appSettingsGet} from 'Storage/Settings'; import { appSettingsGet } from 'Storage/Settings';
import * as Local from 'Storage/Client'; import * as Local from 'Storage/Client';
import FolderStore from 'Stores/User/Folder'; import FolderStore from 'Stores/User/Folder';
@ -15,21 +14,19 @@ import FolderStore from 'Stores/User/Folder';
import Promises from 'Promises/User/Ajax'; import Promises from 'Promises/User/Ajax';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
class FoldersUserSettings class FoldersUserSettings {
{
constructor() { constructor() {
this.displaySpecSetting = FolderStore.displaySpecSetting; this.displaySpecSetting = FolderStore.displaySpecSetting;
this.folderList = FolderStore.folderList; this.folderList = FolderStore.folderList;
this.folderListHelp = ko.observable('').extend({throttle: Magics.Time100ms}); this.folderListHelp = ko.observable('').extend({ throttle: Magics.Time100ms });
this.loading = ko.computed(() => { this.loading = ko.computed(() => {
const const loading = FolderStore.foldersLoading(),
loading = FolderStore.foldersLoading(),
creating = FolderStore.foldersCreating(), creating = FolderStore.foldersCreating(),
deleting = FolderStore.foldersDeleting(), deleting = FolderStore.foldersDeleting(),
renaming = FolderStore.foldersRenaming(); renaming = FolderStore.foldersRenaming();
@ -39,7 +36,7 @@ class FoldersUserSettings
this.folderForDeletion = ko.observable(null).deleteAccessHelper(); this.folderForDeletion = ko.observable(null).deleteAccessHelper();
this.folderForEdit = ko.observable(null).extend({toggleSubscribeProperty: [this, 'edited']}); this.folderForEdit = ko.observable(null).extend({ toggleSubscribeProperty: [this, 'edited'] });
this.useImapSubscribe = !!appSettingsGet('useImapSubscribe'); this.useImapSubscribe = !!appSettingsGet('useImapSubscribe');
} }
@ -47,8 +44,7 @@ class FoldersUserSettings
folderEditOnEnter(folder) { folderEditOnEnter(folder) {
const nameToEdit = folder ? trim(folder.nameForEdit()) : ''; const nameToEdit = folder ? trim(folder.nameForEdit()) : '';
if ('' !== nameToEdit && folder.name() !== nameToEdit) if ('' !== nameToEdit && folder.name() !== nameToEdit) {
{
Local.set(ClientSideKeyName.FoldersLashHash, ''); Local.set(ClientSideKeyName.FoldersLashHash, '');
getApp().foldersPromisesActionHelper( getApp().foldersPromisesActionHelper(
@ -65,8 +61,7 @@ class FoldersUserSettings
} }
folderEditOnEsc(folder) { folderEditOnEsc(folder) {
if (folder) if (folder) {
{
folder.edited(false); folder.edited(false);
} }
} }
@ -100,22 +95,22 @@ class FoldersUserSettings
} }
deleteFolder(folderToRemove) { deleteFolder(folderToRemove) {
if (folderToRemove && folderToRemove.canBeDeleted() && folderToRemove.deleteAccess() && if (
0 === folderToRemove.privateMessageCountAll()) folderToRemove &&
{ folderToRemove.canBeDeleted() &&
folderToRemove.deleteAccess() &&
0 === folderToRemove.privateMessageCountAll()
) {
this.folderForDeletion(null); this.folderForDeletion(null);
if (folderToRemove) if (folderToRemove) {
{ const fRemoveFolder = function(folder) {
const if (folderToRemove === folder) {
fRemoveFolder = function(folder) { return true;
if (folderToRemove === folder) }
{ folder.subFolders.remove(fRemoveFolder);
return true; return false;
} };
folder.subFolders.remove(fRemoveFolder);
return false;
};
Local.set(ClientSideKeyName.FoldersLashHash, ''); Local.set(ClientSideKeyName.FoldersLashHash, '');
@ -128,9 +123,7 @@ class FoldersUserSettings
removeFolderFromCacheList(folderToRemove.fullNameRaw); removeFolderFromCacheList(folderToRemove.fullNameRaw);
} }
} } else if (0 < folderToRemove.privateMessageCountAll()) {
else if (0 < folderToRemove.privateMessageCountAll())
{
FolderStore.folderList.error(getNotification(Notification.CantDeleteNonEmptyFolder)); FolderStore.folderList.error(getNotification(Notification.CantDeleteNonEmptyFolder));
} }
} }
@ -158,4 +151,4 @@ class FoldersUserSettings
} }
} }
export {FoldersUserSettings, FoldersUserSettings as default}; export { FoldersUserSettings, FoldersUserSettings as default };

View file

@ -1,20 +1,16 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {MESSAGES_PER_PAGE_VALUES} from 'Common/Consts'; import { MESSAGES_PER_PAGE_VALUES } from 'Common/Consts';
import {bAnimationSupported} from 'Common/Globals'; import { bAnimationSupported } from 'Common/Globals';
import {SaveSettingsStep, Magics, EditorDefaultType, Layout} from 'Common/Enums'; import { SaveSettingsStep, Magics, EditorDefaultType, Layout } from 'Common/Enums';
import { import { settingsSaveHelperSimpleFunction, convertLangName, isArray, timeOutAction, boolToAjax } from 'Common/Utils';
settingsSaveHelperSimpleFunction,
convertLangName, isArray, timeOutAction, boolToAjax
} from 'Common/Utils';
import {i18n, trigger as translatorTrigger, reload as translatorReload} from 'Common/Translator'; import { i18n, trigger as translatorTrigger, reload as translatorReload } from 'Common/Translator';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
import AppStore from 'Stores/User/App'; import AppStore from 'Stores/User/App';
import LanguageStore from 'Stores/Language'; import LanguageStore from 'Stores/Language';
@ -25,8 +21,7 @@ import MessageStore from 'Stores/User/Message';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
class GeneralUserSettings class GeneralUserSettings {
{
constructor() { constructor() {
this.language = LanguageStore.language; this.language = LanguageStore.language;
this.languages = LanguageStore.languages; this.languages = LanguageStore.languages;
@ -52,7 +47,7 @@ class GeneralUserSettings
this.allowLanguagesOnSettings = AppStore.allowLanguagesOnSettings; this.allowLanguagesOnSettings = AppStore.allowLanguagesOnSettings;
this.languageFullName = ko.computed(() => convertLangName(this.language())); this.languageFullName = ko.computed(() => convertLangName(this.language()));
this.languageTrigger = ko.observable(SaveSettingsStep.Idle).extend({throttle: Magics.Time100ms}); this.languageTrigger = ko.observable(SaveSettingsStep.Idle).extend({ throttle: Magics.Time100ms });
this.mppTrigger = ko.observable(SaveSettingsStep.Idle); this.mppTrigger = ko.observable(SaveSettingsStep.Idle);
this.editorDefaultTypeTrigger = ko.observable(SaveSettingsStep.Idle); this.editorDefaultTypeTrigger = ko.observable(SaveSettingsStep.Idle);
@ -75,27 +70,26 @@ class GeneralUserSettings
this.editorDefaultTypes = ko.computed(() => { this.editorDefaultTypes = ko.computed(() => {
translatorTrigger(); translatorTrigger();
return [ return [
{'id': EditorDefaultType.Html, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML')}, { 'id': EditorDefaultType.Html, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML') },
{'id': EditorDefaultType.Plain, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN')}, { 'id': EditorDefaultType.Plain, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN') },
{'id': EditorDefaultType.HtmlForced, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML_FORCED')}, { 'id': EditorDefaultType.HtmlForced, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML_FORCED') },
{'id': EditorDefaultType.PlainForced, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN_FORCED')} { 'id': EditorDefaultType.PlainForced, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN_FORCED') }
]; ];
}); });
this.layoutTypes = ko.computed(() => { this.layoutTypes = ko.computed(() => {
translatorTrigger(); translatorTrigger();
return [ return [
{'id': Layout.NoPreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_NO_SPLIT')}, { 'id': Layout.NoPreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_NO_SPLIT') },
{'id': Layout.SidePreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_VERTICAL_SPLIT')}, { 'id': Layout.SidePreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_VERTICAL_SPLIT') },
{'id': Layout.BottomPreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_HORIZONTAL_SPLIT')} { 'id': Layout.BottomPreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_HORIZONTAL_SPLIT') }
]; ];
}); });
} }
editMainIdentity() { editMainIdentity() {
const identity = this.identityMain(); const identity = this.identityMain();
if (identity) if (identity) {
{
showScreenPopup(require('View/Popup/Identity'), [identity]); showScreenPopup(require('View/Popup/Identity'), [identity]);
} }
} }
@ -106,8 +100,7 @@ class GeneralUserSettings
onBuild() { onBuild() {
_.delay(() => { _.delay(() => {
const const f0 = settingsSaveHelperSimpleFunction(this.editorDefaultTypeTrigger, this),
f0 = settingsSaveHelperSimpleFunction(this.editorDefaultTypeTrigger, this),
f1 = settingsSaveHelperSimpleFunction(this.mppTrigger, this), f1 = settingsSaveHelperSimpleFunction(this.mppTrigger, this),
f2 = settingsSaveHelperSimpleFunction(this.layoutTrigger, this), f2 = settingsSaveHelperSimpleFunction(this.layoutTrigger, this),
fReloadLanguageHelper = (saveSettingsStep) => () => { fReloadLanguageHelper = (saveSettingsStep) => () => {
@ -117,15 +110,13 @@ class GeneralUserSettings
this.language.subscribe((value) => { this.language.subscribe((value) => {
this.languageTrigger(SaveSettingsStep.Animate); this.languageTrigger(SaveSettingsStep.Animate);
translatorReload(false, value).then( translatorReload(false, value)
fReloadLanguageHelper(SaveSettingsStep.TrueResult), .then(fReloadLanguageHelper(SaveSettingsStep.TrueResult), fReloadLanguageHelper(SaveSettingsStep.FalseResult))
fReloadLanguageHelper(SaveSettingsStep.FalseResult) .then(() => {
).then(() => { Remote.saveSettings(null, {
Remote.saveSettings(null, { 'Language': value
'Language': value });
}); });
});
}); });
this.editorDefaultType.subscribe(Remote.saveSettingsHelper('EditorDefaultType', null, f0)); this.editorDefaultType.subscribe(Remote.saveSettingsHelper('EditorDefaultType', null, f0));
@ -135,27 +126,39 @@ class GeneralUserSettings
this.useCheckboxesInList.subscribe(Remote.saveSettingsHelper('UseCheckboxesInList', boolToAjax)); this.useCheckboxesInList.subscribe(Remote.saveSettingsHelper('UseCheckboxesInList', boolToAjax));
this.enableDesktopNotification.subscribe((value) => { this.enableDesktopNotification.subscribe((value) => {
timeOutAction('SaveDesktopNotifications', () => { timeOutAction(
Remote.saveSettings(null, { 'SaveDesktopNotifications',
'DesktopNotifications': boolToAjax(value) () => {
}); Remote.saveSettings(null, {
}, Magics.Time3s); 'DesktopNotifications': boolToAjax(value)
});
},
Magics.Time3s
);
}); });
this.enableSoundNotification.subscribe((value) => { this.enableSoundNotification.subscribe((value) => {
timeOutAction('SaveSoundNotification', () => { timeOutAction(
Remote.saveSettings(null, { 'SaveSoundNotification',
'SoundNotification': boolToAjax(value) () => {
}); Remote.saveSettings(null, {
}, Magics.Time3s); 'SoundNotification': boolToAjax(value)
});
},
Magics.Time3s
);
}); });
this.replySameFolder.subscribe((value) => { this.replySameFolder.subscribe((value) => {
timeOutAction('SaveReplySameFolder', () => { timeOutAction(
Remote.saveSettings(null, { 'SaveReplySameFolder',
'ReplySameFolder': boolToAjax(value) () => {
}); Remote.saveSettings(null, {
}, Magics.Time3s); 'ReplySameFolder': boolToAjax(value)
});
},
Magics.Time3s
);
}); });
this.useThreads.subscribe((value) => { this.useThreads.subscribe((value) => {
@ -179,10 +182,8 @@ class GeneralUserSettings
} }
selectLanguage() { selectLanguage() {
showScreenPopup(require('View/Popup/Languages'), [ showScreenPopup(require('View/Popup/Languages'), [this.language, this.languages(), LanguageStore.userLanguage()]);
this.language, this.languages(), LanguageStore.userLanguage()
]);
} }
} }
export {GeneralUserSettings, GeneralUserSettings as default}; export { GeneralUserSettings, GeneralUserSettings as default };

View file

@ -1,22 +1,20 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {delegateRunOnDestroy, boolToAjax} from 'Common/Utils'; import { delegateRunOnDestroy, boolToAjax } from 'Common/Utils';
import {Magics} from 'Common/Enums'; import { Magics } from 'Common/Enums';
import {bIsHttps} from 'Common/Globals'; import { bIsHttps } from 'Common/Globals';
import PgpStore from 'Stores/User/Pgp'; import PgpStore from 'Stores/User/Pgp';
import SettingsStore from 'Stores/User/Settings'; import SettingsStore from 'Stores/User/Settings';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
class OpenPgpUserSettings class OpenPgpUserSettings {
{
constructor() { constructor() {
this.openpgpkeys = PgpStore.openpgpkeys; this.openpgpkeys = PgpStore.openpgpkeys;
this.openpgpkeysPublic = PgpStore.openpgpkeysPublic; this.openpgpkeysPublic = PgpStore.openpgpkeysPublic;
@ -38,8 +36,7 @@ class OpenPgpUserSettings
} }
viewOpenPgpKey(openPgpKey) { viewOpenPgpKey(openPgpKey) {
if (openPgpKey) if (openPgpKey) {
{
showScreenPopup(require('View/Popup/ViewOpenPgpKey'), [openPgpKey]); showScreenPopup(require('View/Popup/ViewOpenPgpKey'), [openPgpKey]);
} }
} }
@ -49,21 +46,16 @@ class OpenPgpUserSettings
* @returns {void} * @returns {void}
*/ */
deleteOpenPgpKey(openPgpKeyToRemove) { deleteOpenPgpKey(openPgpKeyToRemove) {
if (openPgpKeyToRemove && openPgpKeyToRemove.deleteAccess()) if (openPgpKeyToRemove && openPgpKeyToRemove.deleteAccess()) {
{
this.openPgpKeyForDeletion(null); this.openPgpKeyForDeletion(null);
if (openPgpKeyToRemove && PgpStore.openpgpKeyring) if (openPgpKeyToRemove && PgpStore.openpgpKeyring) {
{
const findedItem = _.find(PgpStore.openpgpkeys(), (key) => openPgpKeyToRemove === key); const findedItem = _.find(PgpStore.openpgpkeys(), (key) => openPgpKeyToRemove === key);
if (findedItem) if (findedItem) {
{
PgpStore.openpgpkeys.remove(findedItem); PgpStore.openpgpkeys.remove(findedItem);
delegateRunOnDestroy(findedItem); delegateRunOnDestroy(findedItem);
PgpStore PgpStore.openpgpKeyring[findedItem.isPrivate ? 'privateKeys' : 'publicKeys'].removeForId(findedItem.guid);
.openpgpKeyring[findedItem.isPrivate ? 'privateKeys' : 'publicKeys']
.removeForId(findedItem.guid);
PgpStore.openpgpKeyring.store(); PgpStore.openpgpKeyring.store();
} }
@ -75,13 +67,9 @@ class OpenPgpUserSettings
onBuild() { onBuild() {
_.delay(() => { _.delay(() => {
this.allowDraftAutosave.subscribe(Remote.saveSettingsHelper('AllowDraftAutosave', boolToAjax));
this.allowDraftAutosave.subscribe(
Remote.saveSettingsHelper('AllowDraftAutosave', boolToAjax)
);
}, Magics.Time50ms); }, Magics.Time50ms);
} }
} }
export {OpenPgpUserSettings, OpenPgpUserSettings as default}; export { OpenPgpUserSettings, OpenPgpUserSettings as default };

View file

@ -1,21 +1,19 @@
import _ from '_'; import _ from '_';
import ko from 'ko'; import ko from 'ko';
import {pInt, settingsSaveHelperSimpleFunction} from 'Common/Utils'; import { pInt, settingsSaveHelperSimpleFunction } from 'Common/Utils';
import {Capa, SaveSettingsStep} from 'Common/Enums'; import { Capa, SaveSettingsStep } from 'Common/Enums';
import {i18n, trigger as translatorTrigger} from 'Common/Translator'; import { i18n, trigger as translatorTrigger } from 'Common/Translator';
import {capa} from 'Storage/Settings'; import { capa } from 'Storage/Settings';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
import SettinsStore from 'Stores/User/Settings'; import SettinsStore from 'Stores/User/Settings';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
class SecurityUserSettings class SecurityUserSettings {
{
constructor() { constructor() {
this.capaAutoLogout = capa(Capa.AutoLogout); this.capaAutoLogout = capa(Capa.AutoLogout);
this.capaTwoFactor = capa(Capa.TwoFactor); this.capaTwoFactor = capa(Capa.TwoFactor);
@ -26,14 +24,14 @@ class SecurityUserSettings
this.autoLogoutOptions = ko.computed(() => { this.autoLogoutOptions = ko.computed(() => {
translatorTrigger(); translatorTrigger();
return [ return [
{'id': 0, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_NEVER_OPTION_NAME')}, { 'id': 0, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_NEVER_OPTION_NAME') },
{'id': 5, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 5})}, { 'id': 5, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', { 'MINUTES': 5 }) },
{'id': 10, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 10})}, { 'id': 10, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', { 'MINUTES': 10 }) },
{'id': 30, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 30})}, { 'id': 30, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', { 'MINUTES': 30 }) },
{'id': 60, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 60})}, { 'id': 60, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', { 'MINUTES': 60 }) },
{'id': 60 * 2, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 2})}, { 'id': 60 * 2, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', { 'HOURS': 2 }) },
{'id': 60 * 5, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 5})}, { 'id': 60 * 5, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', { 'HOURS': 5 }) },
{'id': 60 * 10, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 10})} { 'id': 60 * 10, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', { 'HOURS': 10 }) }
]; ];
}); });
} }
@ -43,8 +41,7 @@ class SecurityUserSettings
} }
onBuild() { onBuild() {
if (this.capaAutoLogout) if (this.capaAutoLogout) {
{
_.delay(() => { _.delay(() => {
const f0 = settingsSaveHelperSimpleFunction(this.autoLogout.trigger, this); const f0 = settingsSaveHelperSimpleFunction(this.autoLogout.trigger, this);
@ -54,4 +51,4 @@ class SecurityUserSettings
} }
} }
export {SecurityUserSettings, SecurityUserSettings as default}; export { SecurityUserSettings, SecurityUserSettings as default };

View file

@ -1,12 +1,10 @@
import SocialStore from 'Stores/Social'; import SocialStore from 'Stores/Social';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
import {command} from 'Knoin/Knoin'; import { command } from 'Knoin/Knoin';
class SocialUserSettings class SocialUserSettings {
{
constructor() { constructor() {
this.googleEnable = SocialStore.google.enabled; this.googleEnable = SocialStore.google.enabled;
this.googleEnableAuth = SocialStore.google.capa.auth; this.googleEnableAuth = SocialStore.google.capa.auth;
@ -33,8 +31,7 @@ class SocialUserSettings
@command((self) => !self.googleLoggined() && !self.googleActions()) @command((self) => !self.googleLoggined() && !self.googleActions())
connectGoogleCommand() { connectGoogleCommand() {
if (!this.googleLoggined()) if (!this.googleLoggined()) {
{
getApp().googleConnect(); getApp().googleConnect();
} }
} }
@ -46,8 +43,7 @@ class SocialUserSettings
@command((self) => !self.facebookLoggined() && !self.facebookActions()) @command((self) => !self.facebookLoggined() && !self.facebookActions())
connectFacebookCommand() { connectFacebookCommand() {
if (!this.facebookLoggined()) if (!this.facebookLoggined()) {
{
getApp().facebookConnect(); getApp().facebookConnect();
} }
} }
@ -59,8 +55,7 @@ class SocialUserSettings
@command((self) => !self.twitterLoggined() && !self.twitterActions()) @command((self) => !self.twitterLoggined() && !self.twitterActions())
connectTwitterCommand() { connectTwitterCommand() {
if (!this.twitterLoggined()) if (!this.twitterLoggined()) {
{
getApp().twitterConnect(); getApp().twitterConnect();
} }
} }
@ -71,4 +66,4 @@ class SocialUserSettings
} }
} }
export {SocialUserSettings, SocialUserSettings as default}; export { SocialUserSettings, SocialUserSettings as default };

View file

@ -1,21 +1,21 @@
import ko from 'ko'; import ko from 'ko';
import {i18n} from 'Common/Translator'; import { i18n } from 'Common/Translator';
import TemplateStore from 'Stores/User/Template'; import TemplateStore from 'Stores/User/Template';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
import {getApp} from 'Helper/Apps/User'; import { getApp } from 'Helper/Apps/User';
import {showScreenPopup} from 'Knoin/Knoin'; import { showScreenPopup } from 'Knoin/Knoin';
class TemplatesUserSettings class TemplatesUserSettings {
{
constructor() { constructor() {
this.templates = TemplateStore.templates; this.templates = TemplateStore.templates;
this.processText = ko.computed(() => (TemplateStore.templates.loading() ? i18n('SETTINGS_TEMPLETS/LOADING_PROCESS') : '')); this.processText = ko.computed(() =>
TemplateStore.templates.loading() ? i18n('SETTINGS_TEMPLETS/LOADING_PROCESS') : ''
);
this.visibility = ko.computed(() => ('' === this.processText() ? 'hidden' : 'visible')); this.visibility = ko.computed(() => ('' === this.processText() ? 'hidden' : 'visible'));
this.templateForDeletion = ko.observable(null).deleteAccessHelper(); this.templateForDeletion = ko.observable(null).deleteAccessHelper();
@ -34,19 +34,16 @@ class TemplatesUserSettings
} }
editTemplate(oTemplateItem) { editTemplate(oTemplateItem) {
if (oTemplateItem) if (oTemplateItem) {
{
showScreenPopup(require('View/Popup/Template'), [oTemplateItem]); showScreenPopup(require('View/Popup/Template'), [oTemplateItem]);
} }
} }
deleteTemplate(templateToRemove) { deleteTemplate(templateToRemove) {
if (templateToRemove && templateToRemove.deleteAccess()) if (templateToRemove && templateToRemove.deleteAccess()) {
{
this.templateForDeletion(null); this.templateForDeletion(null);
if (templateToRemove) if (templateToRemove) {
{
this.templates.remove((template) => templateToRemove === template); this.templates.remove((template) => templateToRemove === template);
Remote.templateDelete(() => { Remote.templateDelete(() => {
@ -61,20 +58,18 @@ class TemplatesUserSettings
} }
onBuild(oDom) { onBuild(oDom) {
const self = this; const self = this;
oDom oDom.on('click', '.templates-list .template-item .e-action', function() {
.on('click', '.templates-list .template-item .e-action', function() { // eslint-disable-line prefer-arrow-callback // eslint-disable-line prefer-arrow-callback
const template = ko.dataFor(this); // eslint-disable-line no-invalid-this const template = ko.dataFor(this); // eslint-disable-line no-invalid-this
if (template) if (template) {
{ self.editTemplate(template);
self.editTemplate(template); }
} });
});
this.reloadTemplates(); this.reloadTemplates();
} }
} }
export {TemplatesUserSettings, TemplatesUserSettings as default}; export { TemplatesUserSettings, TemplatesUserSettings as default };

View file

@ -1,23 +1,21 @@
import _ from '_'; import _ from '_';
import $ from '$'; import $ from '$';
import ko from 'ko'; import ko from 'ko';
import Jua from 'Jua'; import Jua from 'Jua';
import {SaveSettingsStep, UploadErrorCode, Capa, Magics} from 'Common/Enums'; import { SaveSettingsStep, UploadErrorCode, Capa, Magics } from 'Common/Enums';
import {changeTheme, convertThemeName} from 'Common/Utils'; import { changeTheme, convertThemeName } from 'Common/Utils';
import {userBackground, themePreviewLink, uploadBackground} from 'Common/Links'; import { userBackground, themePreviewLink, uploadBackground } from 'Common/Links';
import {i18n} from 'Common/Translator'; import { i18n } from 'Common/Translator';
import {capa} from 'Storage/Settings'; import { capa } from 'Storage/Settings';
import ThemeStore from 'Stores/Theme'; import ThemeStore from 'Stores/Theme';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
class ThemesUserSettings class ThemesUserSettings {
{
constructor() { constructor() {
this.theme = ThemeStore.theme; this.theme = ThemeStore.theme;
this.themes = ThemeStore.themes; this.themes = ThemeStore.themes;
@ -32,7 +30,7 @@ class ThemesUserSettings
this.capaUserBackground = ko.observable(capa(Capa.UserBackground)); this.capaUserBackground = ko.observable(capa(Capa.UserBackground));
this.themeTrigger = ko.observable(SaveSettingsStep.Idle).extend({throttle: Magics.Time100ms}); this.themeTrigger = ko.observable(SaveSettingsStep.Idle).extend({ throttle: Magics.Time100ms });
this.iTimer = 0; this.iTimer = 0;
this.oThemeAjaxRequest = null; this.oThemeAjaxRequest = null;
@ -51,18 +49,19 @@ class ThemesUserSettings
this.background.hash.subscribe((value) => { this.background.hash.subscribe((value) => {
const $bg = $('#rl-bg'); const $bg = $('#rl-bg');
if (!value) if (!value) {
{ if ($bg.data('backstretch')) {
if ($bg.data('backstretch'))
{
$bg.backstretch('destroy').attr('style', ''); $bg.backstretch('destroy').attr('style', '');
} }
} } else {
else $bg
{ .attr('style', 'background-image: none !important;')
$bg.attr('style', 'background-image: none !important;').backstretch(userBackground(value), { .backstretch(userBackground(value), {
fade: Magics.Time1s, centeredX: true, centeredY: true fade: Magics.Time1s,
}).removeAttr('style'); centeredX: true,
centeredY: true
})
.removeAttr('style');
} }
}); });
} }
@ -70,12 +69,14 @@ class ThemesUserSettings
onBuild() { onBuild() {
const currentTheme = this.theme(); const currentTheme = this.theme();
this.themesObjects(_.map(this.themes(), (theme) => ({ this.themesObjects(
name: theme, _.map(this.themes(), (theme) => ({
nameDisplay: convertThemeName(theme), name: theme,
selected: ko.observable(theme === currentTheme), nameDisplay: convertThemeName(theme),
themePreviewSrc: themePreviewLink(theme) selected: ko.observable(theme === currentTheme),
}))); themePreviewSrc: themePreviewLink(theme)
}))
);
this.initUploader(); this.initUploader();
} }
@ -85,8 +86,7 @@ class ThemesUserSettings
} }
clearBackground() { clearBackground() {
if (this.capaUserBackground()) if (this.capaUserBackground()) {
{
Remote.clearUserBackground(() => { Remote.clearUserBackground(() => {
this.background.name(''); this.background.name('');
this.background.hash(''); this.background.hash('');
@ -95,18 +95,16 @@ class ThemesUserSettings
} }
initUploader() { initUploader() {
if (this.background.uploaderButton() && this.capaUserBackground()) if (this.background.uploaderButton() && this.capaUserBackground()) {
{ const oJua = new Jua({
const 'action': uploadBackground(),
oJua = new Jua({ 'name': 'uploader',
'action': uploadBackground(), 'queueSize': 1,
'name': 'uploader', 'multipleSizeLimit': 1,
'queueSize': 1, 'disableDragAndDrop': true,
'multipleSizeLimit': 1, 'disableMultiple': true,
'disableDragAndDrop': true, 'clickElement': this.background.uploaderButton()
'disableMultiple': true, });
'clickElement': this.background.uploaderButton()
});
oJua oJua
.on('onStart', () => { .on('onStart', () => {
@ -117,21 +115,16 @@ class ThemesUserSettings
.on('onComplete', (id, result, data) => { .on('onComplete', (id, result, data) => {
this.background.loading(false); this.background.loading(false);
if (result && id && data && data.Result && data.Result.Name && data.Result.Hash) if (result && id && data && data.Result && data.Result.Name && data.Result.Hash) {
{
this.background.name(data.Result.Name); this.background.name(data.Result.Name);
this.background.hash(data.Result.Hash); this.background.hash(data.Result.Hash);
} } else {
else
{
this.background.name(''); this.background.name('');
this.background.hash(''); this.background.hash('');
let errorMsg = ''; let errorMsg = '';
if (data.ErrorCode) if (data.ErrorCode) {
{ switch (data.ErrorCode) {
switch (data.ErrorCode)
{
case UploadErrorCode.FileIsTooBig: case UploadErrorCode.FileIsTooBig:
errorMsg = i18n('SETTINGS_THEMES/ERROR_FILE_IS_TOO_BIG'); errorMsg = i18n('SETTINGS_THEMES/ERROR_FILE_IS_TOO_BIG');
break; break;
@ -142,8 +135,7 @@ class ThemesUserSettings
} }
} }
if (!errorMsg && data.ErrorMessage) if (!errorMsg && data.ErrorMessage) {
{
errorMsg = data.ErrorMessage; errorMsg = data.ErrorMessage;
} }
@ -156,4 +148,4 @@ class ThemesUserSettings
} }
} }
export {ThemesUserSettings, ThemesUserSettings as default}; export { ThemesUserSettings, ThemesUserSettings as default };

View file

@ -1,10 +1,10 @@
import _ from '_'; import _ from '_';
import {CookieDriver} from 'Common/ClientStorageDriver/Cookie'; import { CookieDriver } from 'Common/ClientStorageDriver/Cookie';
import {LocalStorageDriver} from 'Common/ClientStorageDriver/LocalStorage'; import { LocalStorageDriver } from 'Common/ClientStorageDriver/LocalStorage';
const SupportedStorageDriver = _.find( const SupportedStorageDriver = _.find(
[LocalStorageDriver, CookieDriver], (StorageDriver) => StorageDriver && StorageDriver.supported() [LocalStorageDriver, CookieDriver],
(StorageDriver) => StorageDriver && StorageDriver.supported()
); );
const driver = SupportedStorageDriver ? new SupportedStorageDriver() : null; const driver = SupportedStorageDriver ? new SupportedStorageDriver() : null;
@ -14,8 +14,7 @@ const driver = SupportedStorageDriver ? new SupportedStorageDriver() : null;
* @param {*} data * @param {*} data
* @returns {boolean} * @returns {boolean}
*/ */
export function set(key, data) export function set(key, data) {
{
return driver ? driver.set('p' + key, data) : false; return driver ? driver.set('p' + key, data) : false;
} }
@ -23,7 +22,6 @@ export function set(key, data)
* @param {number} key * @param {number} key
* @returns {*} * @returns {*}
*/ */
export function get(key) export function get(key) {
{
return driver ? driver.get('p' + key) : null; return driver ? driver.get('p' + key) : null;
} }

View file

@ -1,4 +1,3 @@
import window from 'window'; import window from 'window';
const STORAGE_KEY = '__rlA'; const STORAGE_KEY = '__rlA';
@ -8,65 +7,55 @@ const TIME_KEY = '__rlT';
* @param {string} storageName * @param {string} storageName
* @returns {boolean} * @returns {boolean}
*/ */
export function isStorageSupported(storageName) export function isStorageSupported(storageName) {
{
let storageIsAvailable = false; let storageIsAvailable = false;
try try {
{
// at: window[storageName] firefox throws SecurityError: The operation is insecure. when in iframe // at: window[storageName] firefox throws SecurityError: The operation is insecure. when in iframe
storageIsAvailable = storageName in window && window[storageName] && window[storageName].setItem; storageIsAvailable = storageName in window && window[storageName] && window[storageName].setItem;
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
if (storageIsAvailable) if (storageIsAvailable) {
{ const s = window[storageName],
const
s = window[storageName],
key = 'testLocalStorage_' + window.Math.random(); key = 'testLocalStorage_' + window.Math.random();
try try {
{
s.setItem(key, key); s.setItem(key, key);
if (key === s.getItem(key)) if (key === s.getItem(key)) {
{
s.removeItem(key); s.removeItem(key);
return true; return true;
} }
} } catch (e) {} // eslint-disable-line no-empty
catch (e) {} // eslint-disable-line no-empty
} }
return false; return false;
} }
const SESS_STORAGE = isStorageSupported('sessionStorage') ? (window.sessionStorage || null) : null; const SESS_STORAGE = isStorageSupported('sessionStorage') ? window.sessionStorage || null : null;
const WIN_STORAGE = window.top || window || null; const WIN_STORAGE = window.top || window || null;
const __get = (key) => { const __get = (key) => {
let result = null; let result = null;
if (SESS_STORAGE) if (SESS_STORAGE) {
{
result = SESS_STORAGE.getItem(key) || null; result = SESS_STORAGE.getItem(key) || null;
} } else if (WIN_STORAGE && window.JSON) {
else if (WIN_STORAGE && window.JSON) const data =
{ WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1)
const data = WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1) ? window.JSON.parse(WIN_STORAGE.name.toString()) : null; ? window.JSON.parse(WIN_STORAGE.name.toString())
result = data ? (data[key] || null) : null; : null;
result = data ? data[key] || null : null;
} }
return result; return result;
}; };
const __set = (key, value) => { const __set = (key, value) => {
if (SESS_STORAGE) {
if (SESS_STORAGE)
{
SESS_STORAGE.setItem(key, value); SESS_STORAGE.setItem(key, value);
} } else if (WIN_STORAGE && window.JSON) {
else if (WIN_STORAGE && window.JSON) let data =
{ WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1)
let data = WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1) ? window.JSON.parse(WIN_STORAGE.name.toString()) : null; ? window.JSON.parse(WIN_STORAGE.name.toString())
: null;
data = data || {}; data = data || {};
data[key] = value; data[key] = value;
@ -74,30 +63,27 @@ const __set = (key, value) => {
} }
}; };
const timestamp = () => window.Math.round((new window.Date()).getTime() / 1000); const timestamp = () => window.Math.round(new window.Date().getTime() / 1000);
const setTimestamp = () => __set(TIME_KEY, timestamp()); const setTimestamp = () => __set(TIME_KEY, timestamp());
const getTimestamp = () => { const getTimestamp = () => {
const time = __get(TIME_KEY, 0); const time = __get(TIME_KEY, 0);
return time ? (window.parseInt(time, 10) || 0) : 0; return time ? window.parseInt(time, 10) || 0 : 0;
}; };
/** /**
* @returns {string} * @returns {string}
*/ */
export function getHash() export function getHash() {
{
return __get(STORAGE_KEY); return __get(STORAGE_KEY);
} }
/** /**
* @returns {void} * @returns {void}
*/ */
export function setHash() export function setHash() {
{ const key = 'AuthAccountHash',
const
key = 'AuthAccountHash',
appData = window.__rlah_data(); appData = window.__rlah_data();
__set(STORAGE_KEY, appData && appData[key] ? appData[key] : ''); __set(STORAGE_KEY, appData && appData[key] ? appData[key] : '');
@ -107,8 +93,7 @@ export function setHash()
/** /**
* @returns {void} * @returns {void}
*/ */
export function clearHash() export function clearHash() {
{
__set(STORAGE_KEY, ''); __set(STORAGE_KEY, '');
setTimestamp(); setTimestamp();
} }
@ -116,10 +101,9 @@ export function clearHash()
/** /**
* @returns {boolean} * @returns {boolean}
*/ */
export function checkTimestamp() export function checkTimestamp() {
{ if (timestamp() > getTimestamp() + 1000 * 60 * 60) {
if (timestamp() > getTimestamp() + 1000 * 60 * 60) // 60m // 60m
{
clearHash(); clearHash();
return true; return true;
} }

View file

@ -1,6 +1,5 @@
import window from 'window'; import window from 'window';
import {isUnd, isNormal, isArray, inArray} from 'Common/Utils'; import { isUnd, isNormal, isArray, inArray } from 'Common/Utils';
let SETTINGS = window.__rlah_data() || null; let SETTINGS = window.__rlah_data() || null;
SETTINGS = isNormal(SETTINGS) ? SETTINGS : {}; SETTINGS = isNormal(SETTINGS) ? SETTINGS : {};
@ -12,8 +11,7 @@ APP_SETTINGS = isNormal(APP_SETTINGS) ? APP_SETTINGS : {};
* @param {string} name * @param {string} name
* @returns {*} * @returns {*}
*/ */
export function settingsGet(name) export function settingsGet(name) {
{
return isUnd(SETTINGS[name]) ? null : SETTINGS[name]; return isUnd(SETTINGS[name]) ? null : SETTINGS[name];
} }
@ -21,8 +19,7 @@ export function settingsGet(name)
* @param {string} name * @param {string} name
* @param {*} value * @param {*} value
*/ */
export function settingsSet(name, value) export function settingsSet(name, value) {
{
SETTINGS[name] = value; SETTINGS[name] = value;
} }
@ -30,8 +27,7 @@ export function settingsSet(name, value)
* @param {string} name * @param {string} name
* @returns {*} * @returns {*}
*/ */
export function appSettingsGet(name) export function appSettingsGet(name) {
{
return isUnd(APP_SETTINGS[name]) ? null : APP_SETTINGS[name]; return isUnd(APP_SETTINGS[name]) ? null : APP_SETTINGS[name];
} }
@ -39,8 +35,7 @@ export function appSettingsGet(name)
* @param {string} name * @param {string} name
* @returns {boolean} * @returns {boolean}
*/ */
export function capa(name) export function capa(name) {
{
const values = settingsGet('Capa'); const values = settingsGet('Capa');
return isArray(values) && isNormal(name) && -1 < inArray(name, values); return isArray(values) && isNormal(name) && -1 < inArray(name, values);
} }

View file

@ -1,10 +1,8 @@
import ko from 'ko'; import ko from 'ko';
import {$html, bMobileDevice} from 'Common/Globals'; import { $html, bMobileDevice } from 'Common/Globals';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
class AbstractAppStore class AbstractAppStore {
{
constructor() { constructor() {
this.allowLanguagesOnSettings = ko.observable(true); this.allowLanguagesOnSettings = ko.observable(true);
this.allowLanguagesOnLogin = ko.observable(true); this.allowLanguagesOnLogin = ko.observable(true);
@ -35,4 +33,4 @@ class AbstractAppStore
} }
} }
export {AbstractAppStore, AbstractAppStore as default}; export { AbstractAppStore, AbstractAppStore as default };

View file

@ -1,12 +1,10 @@
import window from 'window'; import window from 'window';
import $ from '$'; import $ from '$';
import ko from 'ko'; import ko from 'ko';
import {settingsGet} from 'Storage/Settings'; import { settingsGet } from 'Storage/Settings';
import {AbstractAppStore} from 'Stores/AbstractApp'; import { AbstractAppStore } from 'Stores/AbstractApp';
class AppAdminStore extends AbstractAppStore class AppAdminStore extends AbstractAppStore {
{
constructor() { constructor() {
super(); super();

Some files were not shown because too many files have changed in this diff Show more