Code refactoring (v2)

This commit is contained in:
RainLoop Team 2016-06-17 02:23:49 +03:00
parent 90d95d3ca4
commit 80ab02363e
29 changed files with 858 additions and 857 deletions

View file

@ -12,7 +12,7 @@ import {noop, isNormal, pString, inArray, microtime, timestamp, detectDropdownVi
import * as Links from 'Common/Links'; import * as Links from 'Common/Links';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
import * as Events from 'Common/Events'; import * as Events from 'Common/Events';
import Translator from 'Common/Translator'; import {initOnStartOrLangChange, initNotificationLanguage} from 'Common/Translator';
import {AbstractBoot} from 'Knoin/AbstractBoot'; import {AbstractBoot} from 'Knoin/AbstractBoot';
@ -307,7 +307,7 @@ class AbstractApp extends AbstractBoot
ko.components.register('CheckboxSimple', require('Component/Checkbox')); ko.components.register('CheckboxSimple', require('Component/Checkbox'));
} }
Translator.initOnStartOrLangChange(Translator.initNotificationLanguage, Translator); initOnStartOrLangChange(initNotificationLanguage);
_.delay(windowResizeCallback, 1000); _.delay(windowResizeCallback, 1000);

View file

@ -4,7 +4,7 @@ import ko from 'ko';
import progressJs from 'progressJs'; import progressJs from 'progressJs';
import * as Links from 'Common/Links'; import * as Links from 'Common/Links';
import Translator 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';
@ -186,14 +186,14 @@ class AdminApp extends AbstractApp
Notification.LicensingExpired Notification.LicensingExpired
])) ]))
{ {
LicenseStore.licenseError(Translator.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(Translator.getNotification(Notification.LicensingServerIsUnavailable)); LicenseStore.licenseError(getNotification(Notification.LicensingServerIsUnavailable));
LicenseStore.licensing(true); LicenseStore.licensing(true);
} }
else else
@ -256,5 +256,4 @@ class AdminApp extends AbstractApp
} }
} }
const App = new AdminApp(); export default new AdminApp();
export default App;

View file

@ -24,8 +24,8 @@ import * as Plugins from 'Common/Plugins';
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 * as Momentor from 'Common/Momentor'; import * as Momentor from 'Common/Momentor';
import Translator from 'Common/Translator'; import * as Cache from 'Common/Cache';
import Cache from 'Common/Cache'; import {getNotification, i18n} from 'Common/Translator';
import SocialStore from 'Stores/Social'; import SocialStore from 'Stores/Social';
import SettingsStore from 'Stores/User/Settings'; import SettingsStore from 'Stores/User/Settings';
@ -37,9 +37,9 @@ import PgpStore from 'Stores/User/Pgp';
import MessageStore from 'Stores/User/Message'; import MessageStore from 'Stores/User/Message';
import ContactStore from 'Stores/User/Contact'; import ContactStore from 'Stores/User/Contact';
import Local from 'Storage/Client'; import * as Local from 'Storage/Client';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
import RainLoopStorage from 'Storage/RainLoop'; import {checkTimestamp} from 'Storage/RainLoop';
import Remote from 'Remote/User/Ajax'; import Remote from 'Remote/User/Ajax';
import Promises from 'Promises/User/Ajax'; import Promises from 'Promises/User/Ajax';
@ -81,7 +81,7 @@ class AppUser extends AbstractApp
window.setTimeout(() => window.setInterval(() => Events.pub('interval.10m-after5m'), 60000 * 10), 60000 * 5); window.setTimeout(() => window.setInterval(() => Events.pub('interval.10m-after5m'), 60000 * 10), 60000 * 5);
$.wakeUp(() => { $.wakeUp(() => {
if (RainLoopStorage.checkTimestamp()) if (checkTimestamp())
{ {
this.reload(); this.reload();
} }
@ -95,7 +95,7 @@ class AppUser extends AbstractApp
}, {}, 60 * 60 * 1000); }, {}, 60 * 60 * 1000);
if (RainLoopStorage.checkTimestamp()) if (checkTimestamp())
{ {
this.reload(); this.reload();
} }
@ -189,7 +189,7 @@ class AppUser extends AbstractApp
MessageStore.messageList([]); MessageStore.messageList([]);
MessageStore.messageListLoading(false); MessageStore.messageListLoading(false);
MessageStore.messageListError(oData && oData.ErrorCode ? MessageStore.messageListError(oData && oData.ErrorCode ?
Translator.getNotification(oData.ErrorCode) : Translator.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST') getNotification(oData.ErrorCode) : i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST')
); );
} }
@ -298,7 +298,7 @@ class AppUser extends AbstractApp
if (oData && -1 < inArray(oData.ErrorCode, if (oData && -1 < inArray(oData.ErrorCode,
[Notification.CantMoveMessage, Notification.CantCopyMessage])) [Notification.CantMoveMessage, Notification.CantCopyMessage]))
{ {
window.alert(Translator.getNotification(oData.ErrorCode)); window.alert(getNotification(oData.ErrorCode));
} }
} }
@ -366,7 +366,7 @@ class AppUser extends AbstractApp
else if (!bUseFolder || (FolderType.Trash === iDeleteType && else if (!bUseFolder || (FolderType.Trash === iDeleteType &&
(sFromFolderFullNameRaw === FolderStore.spamFolder() || sFromFolderFullNameRaw === FolderStore.trashFolder()))) (sFromFolderFullNameRaw === FolderStore.spamFolder() || sFromFolderFullNameRaw === FolderStore.trashFolder())))
{ {
kn.showScreenPopup(require('View/Popup/Ask'), [Translator.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), () => { kn.showScreenPopup(require('View/Popup/Ask'), [i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), () => {
this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove); this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
MessageStore.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove); MessageStore.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
}]); }]);
@ -437,7 +437,7 @@ class AppUser extends AbstractApp
.fastResolve(true) .fastResolve(true)
.then(() => promise) .then(() => promise)
.catch((errorCode) => { .catch((errorCode) => {
FolderStore.folderList.error(Translator.getNotification(errorCode, '', errorDefCode)); FolderStore.folderList.error(getNotification(errorCode, '', errorDefCode));
}).fin(() => { }).fin(() => {
Promises.foldersReloadWithTimeout(FolderStore.foldersLoading); Promises.foldersReloadWithTimeout(FolderStore.foldersLoading);
}).done() }).done()
@ -1296,7 +1296,7 @@ class AppUser extends AbstractApp
} }
else else
{ {
this.setWindowTitle(Translator.i18n('TITLES/LOADING')); this.setWindowTitle(i18n('TITLES/LOADING'));
// require.ensure([], function() { // require code splitting // require.ensure([], function() { // require code splitting

View file

@ -2,36 +2,23 @@
import window from 'window'; import window from 'window';
import progressJs from 'progressJs'; import progressJs from 'progressJs';
import RainLoopStorage from 'Storage/RainLoop'; import STYLES_CSS from 'Styles/@Boot.css';
import LAYOUT_HTML from 'Html/Layout.html';
let rlAppDataStorage = null; import {getHash, setHash, clearHash} from 'Storage/RainLoop';
window.__rlah = () => { let RL_APP_DATA_STORAGE = null;
return RainLoopStorage ? RainLoopStorage.getHash() : null;
};
window.__rlah_data = () => { window.__rlah = () => getHash();
return rlAppDataStorage; window.__rlah_set = () => setHash();
}; window.__rlah_clear = () => clearHash();
window.__rlah_data = () => RL_APP_DATA_STORAGE;
window.__rlah_set = () => {
if (RainLoopStorage)
{
RainLoopStorage.setHash();
}
};
window.__rlah_clear = () => {
if (RainLoopStorage)
{
RainLoopStorage.clearHash();
}
};
function getComputedStyle(id, name) function getComputedStyle(id, name)
{ {
var element = window.document.getElementById(id); var element = window.document.getElementById(id);
return element.currentStyle ? element.currentStyle[name] : (window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null); return element.currentStyle ? element.currentStyle[name] :
(window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null);
} }
function includeStyle(styles) function includeStyle(styles)
@ -46,20 +33,16 @@ function includeScr(src)
function includeLayout() function includeLayout()
{ {
const const app = window.document.getElementById('rl-app');
css = require('Styles/@Boot.css'),
layout = require('Html/Layout.html'),
app = window.document.getElementById('rl-app')
;
if (css) if (STYLES_CSS)
{ {
includeStyle(css); includeStyle(STYLES_CSS);
} }
if (app && layout) if (app && LAYOUT_HTML)
{ {
app.innerHTML = layout.replace(/[\r\n\t]+/g, ''); app.innerHTML = LAYOUT_HTML.replace(/[\r\n\t]+/g, '');
return true; return true;
} }
@ -221,21 +204,24 @@ function runApp()
window.__initAppData = function(data) { window.__initAppData = function(data) {
rlAppDataStorage = data; RL_APP_DATA_STORAGE = data;
window.__rlah_set(); window.__rlah_set();
if (rlAppDataStorage.NewThemeLink) if (RL_APP_DATA_STORAGE)
{ {
(window.document.getElementById('app-theme-link') || {}).href = rlAppDataStorage.NewThemeLink; if (RL_APP_DATA_STORAGE.NewThemeLink)
{
(window.document.getElementById('app-theme-link') || {}).href = RL_APP_DATA_STORAGE.NewThemeLink;
} }
if (rlAppDataStorage.IncludeCss) if (RL_APP_DATA_STORAGE.IncludeCss)
{ {
includeStyle(rlAppDataStorage.IncludeCss); includeStyle(RL_APP_DATA_STORAGE.IncludeCss);
} }
showDescriptionAndLoading(rlAppDataStorage ? (rlAppDataStorage.LoadingDescriptionEsc || '') : ''); showDescriptionAndLoading(RL_APP_DATA_STORAGE.LoadingDescriptionEsc || '');
}
runApp(); runApp();
}; };

View file

@ -5,31 +5,25 @@ 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';
class CacheUserStorage let FOLDERS_CACHE = {};
{ let FOLDERS_NAME_CACHE = {};
oFoldersCache = {}; let FOLDERS_HASH_CACHE = {};
oFoldersNamesCache = {}; let FOLDERS_UID_NEXT_CACHE = {};
oFolderHashCache = {}; let MESSAGE_FLAGS_CACHE = {};
oFolderUidNextCache = {};
oMessageListHashCache = {};
oMessageFlagsCache = {};
oNewMessage = {};
oRequestedMessage = {};
bCapaGravatar = false;
inboxFolderName = '';
constructor() let NEW_MESSAGE_CACHE = {};
{ let REQUESTED_MESSAGE_CACHE = {};
this.bCapaGravatar = Settings.capa(Capa.Gravatar);
}
clear() { const capaGravatar = Settings.capa(Capa.Gravatar);
this.oFoldersCache = {}; let inboxFolderName = '';
this.oFoldersNamesCache = {};
this.oFolderHashCache = {}; export function clear()
this.oFolderUidNextCache = {}; {
this.oMessageListHashCache = {}; FOLDERS_CACHE = {};
this.oMessageFlagsCache = {}; FOLDERS_NAME_CACHE = {};
FOLDERS_HASH_CACHE = {};
FOLDERS_UID_NEXT_CACHE = {};
MESSAGE_FLAGS_CACHE = {};
} }
/** /**
@ -37,9 +31,10 @@ class CacheUserStorage
* @param {Function} callback * @param {Function} callback
* @return {string} * @return {string}
*/ */
getUserPic(email, callback) { export function getUserPic(email, callback)
{
email = trim(email); email = trim(email);
callback(this.bCapaGravatar && '' !== email ? Links.avatarLink(email) : '', email); callback(capaGravatar && '' !== email ? Links.avatarLink(email) : '', email);
} }
/** /**
@ -47,7 +42,8 @@ class CacheUserStorage
* @param {string} uid * @param {string} uid
* @return {string} * @return {string}
*/ */
getMessageKey(folderFullNameRaw, uid) { export function getMessageKey(folderFullNameRaw, uid)
{
return `${folderFullNameRaw}#${uid}`; return `${folderFullNameRaw}#${uid}`;
} }
@ -55,8 +51,9 @@ class CacheUserStorage
* @param {string} folder * @param {string} folder
* @param {string} uid * @param {string} uid
*/ */
addRequestedMessage(folder, uid) { export function addRequestedMessage(folder, uid)
this.oRequestedMessage[this.getMessageKey(folder, uid)] = true; {
REQUESTED_MESSAGE_CACHE[getMessageKey(folder, uid)] = true;
} }
/** /**
@ -64,59 +61,66 @@ class CacheUserStorage
* @param {string} uid * @param {string} uid
* @return {boolean} * @return {boolean}
*/ */
hasRequestedMessage(folder, uid) { export function hasRequestedMessage(folder, uid)
return true === this.oRequestedMessage[this.getMessageKey(folder, uid)];
}
/**
* @param {string} folderFullNameRaw
* @param {string} uid
*/
addNewMessageCache(folderFullNameRaw, uid) {
this.oNewMessage[this.getMessageKey(folderFullNameRaw, uid)] = true;
}
/**
* @param {string} folderFullNameRaw
* @param {string} uid
*/
hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid) {
if (this.oNewMessage[this.getMessageKey(folderFullNameRaw, uid)])
{ {
this.oNewMessage[this.getMessageKey(folderFullNameRaw, uid)] = null; return true === REQUESTED_MESSAGE_CACHE[getMessageKey(folder, uid)];
}
/**
* @param {string} folderFullNameRaw
* @param {string} uid
*/
export function addNewMessageCache(folderFullNameRaw, uid)
{
NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)] = true;
}
/**
* @param {string} folderFullNameRaw
* @param {string} uid
*/
export function hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid)
{
if (NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)])
{
NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)] = null;
return true; return true;
} }
return false; return false;
} }
clearNewMessageCache() { export function clearNewMessageCache()
this.oNewMessage = {};
}
/**
* @return {string}
*/
getFolderInboxName() {
return '' === this.inboxFolderName ? 'INBOX' : this.inboxFolderName;
}
/**
* @param {string} folderHash
* @return {string}
*/
getFolderFullNameRaw(folderHash) {
return '' !== folderHash && this.oFoldersNamesCache[folderHash] ? this.oFoldersNamesCache[folderHash] : '';
}
/**
* @param {string} folderHash
* @param {string} folderFullNameRaw
*/
setFolderFullNameRaw(folderHash, folderFullNameRaw) {
this.oFoldersNamesCache[folderHash] = folderFullNameRaw;
if ('INBOX' === folderFullNameRaw || '' === this.inboxFolderName)
{ {
this.inboxFolderName = folderFullNameRaw; NEW_MESSAGE_CACHE = {};
}
/**
* @return {string}
*/
export function getFolderInboxName()
{
return '' === inboxFolderName ? 'INBOX' : inboxFolderName;
}
/**
* @param {string} folderHash
* @return {string}
*/
export function getFolderFullNameRaw(folderHash)
{
return '' !== folderHash && FOLDERS_NAME_CACHE[folderHash] ? FOLDERS_NAME_CACHE[folderHash] : '';
}
/**
* @param {string} folderHash
* @param {string} folderFullNameRaw
*/
export function setFolderFullNameRaw(folderHash, folderFullNameRaw)
{
FOLDERS_NAME_CACHE[folderHash] = folderFullNameRaw;
if ('INBOX' === folderFullNameRaw || '' === inboxFolderName)
{
inboxFolderName = folderFullNameRaw;
} }
} }
@ -124,18 +128,20 @@ class CacheUserStorage
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @return {string} * @return {string}
*/ */
getFolderHash(folderFullNameRaw) { export function getFolderHash(folderFullNameRaw)
return '' !== folderFullNameRaw && this.oFolderHashCache[folderFullNameRaw] ? this.oFolderHashCache[folderFullNameRaw] : ''; {
return '' !== folderFullNameRaw && FOLDERS_HASH_CACHE[folderFullNameRaw] ? FOLDERS_HASH_CACHE[folderFullNameRaw] : '';
} }
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {string} folderHash * @param {string} folderHash
*/ */
setFolderHash(folderFullNameRaw, folderHash) { export function setFolderHash(folderFullNameRaw, folderHash)
{
if ('' !== folderFullNameRaw) if ('' !== folderFullNameRaw)
{ {
this.oFolderHashCache[folderFullNameRaw] = folderHash; FOLDERS_HASH_CACHE[folderFullNameRaw] = folderHash;
} }
} }
@ -143,39 +149,44 @@ class CacheUserStorage
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @return {string} * @return {string}
*/ */
getFolderUidNext(folderFullNameRaw) { export function getFolderUidNext(folderFullNameRaw)
return '' !== folderFullNameRaw && this.oFolderUidNextCache[folderFullNameRaw] ? this.oFolderUidNextCache[folderFullNameRaw] : ''; {
return '' !== folderFullNameRaw && FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] ? FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] : '';
} }
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {string} uidNext * @param {string} uidNext
*/ */
setFolderUidNext(folderFullNameRaw, uidNext) { export function setFolderUidNext(folderFullNameRaw, uidNext)
this.oFolderUidNextCache[folderFullNameRaw] = uidNext; {
FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] = uidNext;
} }
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @return {?FolderModel} * @return {?FolderModel}
*/ */
getFolderFromCacheList(folderFullNameRaw) { export function getFolderFromCacheList(folderFullNameRaw)
return '' !== folderFullNameRaw && this.oFoldersCache[folderFullNameRaw] ? this.oFoldersCache[folderFullNameRaw] : null; {
return '' !== folderFullNameRaw && FOLDERS_CACHE[folderFullNameRaw] ? FOLDERS_CACHE[folderFullNameRaw] : null;
} }
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {?FolderModel} folder * @param {?FolderModel} folder
*/ */
setFolderToCacheList(folderFullNameRaw, folder) { export function setFolderToCacheList(folderFullNameRaw, folder)
this.oFoldersCache[folderFullNameRaw] = folder; {
FOLDERS_CACHE[folderFullNameRaw] = folder;
} }
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
*/ */
removeFolderFromCacheList(folderFullNameRaw) { export function removeFolderFromCacheList(folderFullNameRaw)
this.setFolderToCacheList(folderFullNameRaw, null); {
setFolderToCacheList(folderFullNameRaw, null);
} }
/** /**
@ -183,9 +194,10 @@ class CacheUserStorage
* @param {string} uid * @param {string} uid
* @return {?Array} * @return {?Array}
*/ */
getMessageFlagsFromCache(folderFullName, uid) { export function getMessageFlagsFromCache(folderFullName, uid)
return this.oMessageFlagsCache[folderFullName] && this.oMessageFlagsCache[folderFullName][uid] ? {
this.oMessageFlagsCache[folderFullName][uid] : null; return MESSAGE_FLAGS_CACHE[folderFullName] && MESSAGE_FLAGS_CACHE[folderFullName][uid] ?
MESSAGE_FLAGS_CACHE[folderFullName][uid] : null;
} }
/** /**
@ -193,32 +205,35 @@ class CacheUserStorage
* @param {string} uid * @param {string} uid
* @param {Array} flagsCache * @param {Array} flagsCache
*/ */
setMessageFlagsToCache(folderFullName, uid, flagsCache) { export function setMessageFlagsToCache(folderFullName, uid, flagsCache)
if (!this.oMessageFlagsCache[folderFullName])
{ {
this.oMessageFlagsCache[folderFullName] = {}; if (!MESSAGE_FLAGS_CACHE[folderFullName])
{
MESSAGE_FLAGS_CACHE[folderFullName] = {};
} }
this.oMessageFlagsCache[folderFullName][uid] = flagsCache; MESSAGE_FLAGS_CACHE[folderFullName][uid] = flagsCache;
} }
/** /**
* @param {string} folderFullName * @param {string} folderFullName
*/ */
clearMessageFlagsFromCacheByFolder(folderFullName) { export function clearMessageFlagsFromCacheByFolder(folderFullName)
this.oMessageFlagsCache[folderFullName] = {}; {
MESSAGE_FLAGS_CACHE[folderFullName] = {};
} }
/** /**
* @param {(MessageModel|null)} message * @param {(MessageModel|null)} message
*/ */
initMessageFlagsFromCache(message) { export function initMessageFlagsFromCache(message)
{
if (message) if (message)
{ {
const const
uid = message.uid, uid = message.uid,
flags = this.getMessageFlagsFromCache(message.folderFullNameRaw, uid) flags = getMessageFlagsFromCache(message.folderFullNameRaw, uid)
; ;
if (flags && 0 < flags.length) if (flags && 0 < flags.length)
@ -239,7 +254,7 @@ class CacheUserStorage
{ {
const unseenSubUid = _.find(message.threads(), (sSubUid) => { const unseenSubUid = _.find(message.threads(), (sSubUid) => {
if (uid !== sSubUid) { if (uid !== sSubUid) {
const subFlags = this.getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid); const subFlags = getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid);
return subFlags && 0 < subFlags.length && !!subFlags[0]; return subFlags && 0 < subFlags.length && !!subFlags[0];
} }
return false; return false;
@ -247,7 +262,7 @@ class CacheUserStorage
const flaggedSubUid = _.find(message.threads(), (sSubUid) => { const flaggedSubUid = _.find(message.threads(), (sSubUid) => {
if (uid !== sSubUid) { if (uid !== sSubUid) {
const subFlags = this.getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid); const subFlags = getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid);
return subFlags && 0 < subFlags.length && !!subFlags[1]; return subFlags && 0 < subFlags.length && !!subFlags[1];
} }
return false; return false;
@ -262,10 +277,11 @@ class CacheUserStorage
/** /**
* @param {(MessageModel|null)} message * @param {(MessageModel|null)} message
*/ */
storeMessageFlagsToCache(message) { export function storeMessageFlagsToCache(message)
{
if (message) if (message)
{ {
this.setMessageFlagsToCache( setMessageFlagsToCache(
message.folderFullNameRaw, message.uid, message.folderFullNameRaw, message.uid,
[message.unseen(), message.flagged(), message.answered(), message.forwarded(), [message.unseen(), message.flagged(), message.answered(), message.forwarded(),
message.isReadReceipt(), message.deletedMark()] message.isReadReceipt(), message.deletedMark()]
@ -278,10 +294,11 @@ class CacheUserStorage
* @param {string} uid * @param {string} uid
* @param {Array} flags * @param {Array} flags
*/ */
storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags) { export function storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags)
{
if (isArray(flags) && 0 < flags.length) if (isArray(flags) && 0 < flags.length)
{ {
this.setMessageFlagsToCache(folder, uid, flags); setMessageFlagsToCache(folder, uid, flags);
} }
} }
@ -290,10 +307,11 @@ class CacheUserStorage
* @param {string} uid * @param {string} uid
* @param {number} setAction * @param {number} setAction
*/ */
storeMessageFlagsToCacheBySetAction(folder, uid, setAction) { export function storeMessageFlagsToCacheBySetAction(folder, uid, setAction)
{
let unread = 0; let unread = 0;
const flags = this.getMessageFlagsFromCache(folder, uid); const flags = getMessageFlagsFromCache(folder, uid);
if (isArray(flags) && 0 < flags.length) if (isArray(flags) && 0 < flags.length)
{ {
@ -318,11 +336,8 @@ class CacheUserStorage
break; break;
} }
this.setMessageFlagsToCache(folder, uid, flags); setMessageFlagsToCache(folder, uid, flags);
} }
return unread; return unread;
} }
}
module.exports = new CacheUserStorage();

View file

@ -209,7 +209,8 @@ export const ClientSideKeyName = {
'MessageListSize': 5, 'MessageListSize': 5,
'LastReplyAction': 6, 'LastReplyAction': 6,
'LastSignMe': 7, 'LastSignMe': 7,
'ComposeLastIdentityID': 8 'ComposeLastIdentityID': 8,
'MessageHeaderFullInfo': 9
}; };
/** /**

View file

@ -1,6 +1,6 @@
import {window, $, _, moment} from 'common'; import {window, $, _, moment} from 'common';
import Translator from 'Common/Translator'; import {i18n} from 'Common/Translator';
let _moment = null; let _moment = null;
let _momentNow = 0; let _momentNow = 0;
@ -48,11 +48,11 @@ function formatCustomShortDate(m)
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 Translator.i18n('MESSAGE_LIST/TODAY_AT', { return i18n('MESSAGE_LIST/TODAY_AT', {
TIME: m.format('LT') TIME: m.format('LT')
}); });
case now.clone().subtract('days', 1).format('L') === m.format('L'): case now.clone().subtract('days', 1).format('L') === m.format('L'):
return Translator.i18n('MESSAGE_LIST/YESTERDAY_AT', { return i18n('MESSAGE_LIST/YESTERDAY_AT', {
TIME: m.format('LT') TIME: m.format('LT')
}); });
case now.year() === m.year(): case now.year() === m.year():

View file

@ -2,7 +2,7 @@
import {$, _, key} from 'common'; import {$, _, key} from 'common';
import ko from 'ko'; import ko from 'ko';
import {EventKeyCode} from 'Common/Enums'; import {EventKeyCode} from 'Common/Enums';
import {isArray, inArray} from 'Common/Utils'; import {isArray, inArray, noop, noopTrue} from 'Common/Utils';
class Selector class Selector
{ {
@ -118,9 +118,6 @@ class Selector
this.sLastUid = ''; this.sLastUid = '';
this.oCallbacks = {}; this.oCallbacks = {};
this.emptyFunction = () => {};
this.emptyTrueFunction = () => true;
this.focusedItem.subscribe((item) => { this.focusedItem.subscribe((item) => {
if (item) if (item)
{ {
@ -291,14 +288,14 @@ class Selector
{ {
if (!item) if (!item)
{ {
(this.oCallbacks.onItemSelect || this.emptyFunction)(item || null); (this.oCallbacks.onItemSelect || noop)(item || null);
} }
} }
else else
{ {
if (item) if (item)
{ {
(this.oCallbacks.onItemSelect || this.emptyFunction)(item); (this.oCallbacks.onItemSelect || noop)(item);
} }
} }
} }
@ -416,14 +413,14 @@ class Selector
* @return {boolean} * @return {boolean}
*/ */
autoSelect() { autoSelect() {
return !!(this.oCallbacks.onAutoSelect || this.emptyTrueFunction)(); return !!(this.oCallbacks.onAutoSelect || noopTrue)();
} }
/** /**
* @param {boolean} up * @param {boolean} up
*/ */
doUpUpOrDownDown(up) { doUpUpOrDownDown(up) {
(this.oCallbacks.onUpUpOrDownDown || this.emptyTrueFunction)(!!up); (this.oCallbacks.onUpUpOrDownDown || noopTrue)(!!up);
} }
/** /**

View file

@ -2,129 +2,16 @@
import {window, $, _} from 'common'; import {window, $, _} from 'common';
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, bind, microtime, noop, 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 {langLink} from 'Common/Links';
import Promise from 'Promise';
class Translator let I18N_DATA = window.rainloopI18N || {};
{
data = {};
notificationI18N = {};
constructor() { const I18N_NOTIFICATION_DATA = {};
this.data = window.rainloopI18N || {}; const I18N_NOTIFICATION_MAP = [
this.trigger = ko.observable(false);
this.i18n = bind(this.i18n, this);
this.init();
}
/**
* @param {string} key
* @param {Object=} valueList
* @param {string=} defaulValue
* @return {string}
*/
i18n(key, valueList, defaulValue) {
let
valueName = '',
result = this.data[key]
;
if (isUnd(result))
{
result = isUnd(defaulValue) ? key : defaulValue;
}
if (!isUnd(valueList) && !isNull(valueList))
{
for (valueName in valueList)
{
if (has(valueList, valueName))
{
result = result.replace('%' + valueName + '%', valueList[valueName]);
}
}
}
return result;
}
/**
* @param {Object} element
*/
i18nToNode(element) {
const
$el = $(element),
key = $el.data('i18n')
;
if (key)
{
if ('[' === key.substr(0, 1))
{
switch (key.substr(0, 6))
{
case '[html]':
$el.html(this.i18n(key.substr(6)));
break;
case '[place':
$el.attr('placeholder', this.i18n(key.substr(13)));
break;
case '[title':
$el.attr('title', this.i18n(key.substr(7)));
break;
}
}
else
{
$el.text(this.i18n(key));
}
}
}
/**
* @param {Object} elements
* @param {boolean=} animate = false
*/
i18nToNodes(elements, animate = false) {
_.defer(() => {
$('[data-i18n]', elements).each((index, item) => {
this.i18nToNode(item);
});
if (animate && bAnimationSupported)
{
$('.i18n-animation[data-i18n]', elements).letterfx({
fx: 'fall fade',
backwards: false,
timing: 50,
fx_duration: '50ms',
letter_end: 'restore',
element_end: 'restore'
});
}
});
}
reloadData() {
if (window.rainloopI18N)
{
this.data = window.rainloopI18N || {};
this.i18nToNodes(window.document, true);
require('Common/Momentor').reload();
this.trigger(!this.trigger());
}
window.rainloopI18N = null;
}
initNotificationLanguage() {
const map = [
[Notification.InvalidToken, 'NOTIFICATIONS/INVALID_TOKEN'], [Notification.InvalidToken, 'NOTIFICATIONS/INVALID_TOKEN'],
[Notification.InvalidToken, 'NOTIFICATIONS/INVALID_TOKEN'], [Notification.InvalidToken, 'NOTIFICATIONS/INVALID_TOKEN'],
[Notification.AuthError, 'NOTIFICATIONS/AUTH_ERROR'], [Notification.AuthError, 'NOTIFICATIONS/AUTH_ERROR'],
@ -195,19 +82,125 @@ class Translator
[Notification.UnknownError, 'NOTIFICATIONS/UNKNOWN_ERROR'] [Notification.UnknownError, 'NOTIFICATIONS/UNKNOWN_ERROR']
]; ];
this.notificationI18N = this.notificationI18N || {}; export const trigger = ko.observable(false);
map.forEach((item) => { /**
this.notificationI18N[item[0]] = this.i18n(item[1]); * @param {string} key
* @param {Object=} valueList
* @param {string=} defaulValue
* @return {string}
*/
export function i18n(key, valueList, defaulValue)
{
let
valueName = '',
result = I18N_DATA[key]
;
if (isUnd(result))
{
result = isUnd(defaulValue) ? key : defaulValue;
}
if (!isUnd(valueList) && !isNull(valueList))
{
for (valueName in valueList)
{
if (has(valueList, valueName))
{
result = result.replace('%' + valueName + '%', valueList[valueName]);
}
}
}
return result;
}
const i18nToNode = (element) => {
const
$el = $(element),
key = $el.data('i18n')
;
if (key)
{
if ('[' === key.substr(0, 1))
{
switch (key.substr(0, 6))
{
case '[html]':
$el.html(i18n(key.substr(6)));
break;
case '[place':
$el.attr('placeholder', i18n(key.substr(13)));
break;
case '[title':
$el.attr('title', i18n(key.substr(7)));
break;
}
}
else
{
$el.text(i18n(key));
}
}
};
/**
* @param {Object} elements
* @param {boolean=} animate = false
*/
export function i18nToNodes(elements, animate = false)
{
_.defer(() => {
$('[data-i18n]', elements).each((index, item) => {
i18nToNode(item);
});
if (animate && bAnimationSupported)
{
$('.i18n-animation[data-i18n]', elements).letterfx({
fx: 'fall fade',
backwards: false,
timing: 50,
fx_duration: '50ms',
letter_end: 'restore',
element_end: 'restore'
});
}
});
}
const reloadData = () => {
if (window.rainloopI18N)
{
I18N_DATA = window.rainloopI18N || {};
i18nToNodes(window.document, true);
momentorReload();
trigger(!trigger());
}
window.rainloopI18N = null;
};
export function initNotificationLanguage()
{
I18N_NOTIFICATION_MAP.forEach((item) => {
I18N_NOTIFICATION_DATA[item[0]] = i18n(item[1]);
}); });
} }
/** /**
* @param {Function} callback * @param {Function} callback
* @param {Object} scope * @param {Object} scope
* @param {Function=} langCallback * @param {Function=} langCallback = null
*/ */
initOnStartOrLangChange(callback, scope, langCallback = null) { export function initOnStartOrLangChange(callback, scope, langCallback = null)
{
if (callback) if (callback)
{ {
callback.call(scope); callback.call(scope);
@ -215,7 +208,7 @@ class Translator
if (langCallback) if (langCallback)
{ {
this.trigger.subscribe(() => { trigger.subscribe(() => {
if (callback) if (callback)
{ {
callback.call(scope); callback.call(scope);
@ -226,7 +219,7 @@ class Translator
} }
else if (callback) else if (callback)
{ {
this.trigger.subscribe(callback, scope); trigger.subscribe(callback, scope);
} }
} }
@ -236,7 +229,8 @@ class Translator
* @param {*=} defCode = null * @param {*=} defCode = null
* @return {string} * @return {string}
*/ */
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)
{ {
@ -244,9 +238,9 @@ class Translator
} }
defCode = defCode ? (window.parseInt(defCode, 10)) || 0 : 0; defCode = defCode ? (window.parseInt(defCode, 10)) || 0 : 0;
return isUnd(this.notificationI18N[code]) ? ( return isUnd(I18N_NOTIFICATION_DATA[code]) ? (
defCode && isUnd(this.notificationI18N[defCode]) ? this.notificationI18N[defCode] : '' defCode && isUnd(I18N_NOTIFICATION_DATA[defCode]) ? I18N_NOTIFICATION_DATA[defCode] : ''
) : this.notificationI18N[code]; ) : I18N_NOTIFICATION_DATA[code];
} }
/** /**
@ -254,39 +248,41 @@ class Translator
* @param {number} defCode = Notification.UnknownNotification * @param {number} defCode = Notification.UnknownNotification
* @return {string} * @return {string}
*/ */
getNotificationFromResponse(response, defCode = Notification.UnknownNotification) { export function getNotificationFromResponse(response, defCode = Notification.UnknownNotification)
{
return response && response.ErrorCode ? return response && response.ErrorCode ?
this.getNotification(pInt(response.ErrorCode), response.ErrorMessage || '') : getNotification(pInt(response.ErrorCode), response.ErrorMessage || '') : getNotification(defCode);
this.getNotification(defCode);
} }
/** /**
* @param {*} code * @param {*} code
* @return {string} * @return {string}
*/ */
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 = this.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'); result = i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
break; break;
case UploadErrorCode.FilePartiallyUploaded: case UploadErrorCode.FilePartiallyUploaded:
result = this.i18n('UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED'); result = i18n('UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED');
break; break;
case UploadErrorCode.FileNoUploaded: case UploadErrorCode.FileNoUploaded:
result = this.i18n('UPLOAD/ERROR_NO_FILE_UPLOADED'); result = i18n('UPLOAD/ERROR_NO_FILE_UPLOADED');
break; break;
case UploadErrorCode.MissingTempFolder: case UploadErrorCode.MissingTempFolder:
result = this.i18n('UPLOAD/ERROR_MISSING_TEMP_FOLDER'); result = i18n('UPLOAD/ERROR_MISSING_TEMP_FOLDER');
break; break;
case UploadErrorCode.FileOnSaveingError: case UploadErrorCode.FileOnSaveingError:
result = this.i18n('UPLOAD/ERROR_ON_SAVING_FILE'); result = i18n('UPLOAD/ERROR_ON_SAVING_FILE');
break; break;
case UploadErrorCode.FileType: case UploadErrorCode.FileType:
result = this.i18n('UPLOAD/ERROR_FILE_TYPE'); result = i18n('UPLOAD/ERROR_FILE_TYPE');
break; break;
default: default:
result = this.i18n('UPLOAD/ERROR_UNKNOWN'); result = i18n('UPLOAD/ERROR_UNKNOWN');
break; break;
} }
@ -296,30 +292,22 @@ class Translator
/** /**
* @param {boolean} admin * @param {boolean} admin
* @param {string} language * @param {string} language
* @param {Function=} done
* @param {Function=} fail
*/ */
reload(admin, language, done, fail) { export function reload(admin, language)
{
const const start = microtime();
self = this,
start = microtime()
;
$html.addClass('rl-changing-language'); $html.addClass('rl-changing-language');
return new Promise((resolve, reject) => {
$.ajax({ $.ajax({
url: require('Common/Links').langLink(language, admin), url: langLink(language, admin),
dataType: 'script', dataType: 'script',
cache: true cache: true
}) }).then(() => {
.fail(fail || noop) _.delay(() => {
.done(function () {
_.delay(function () {
self.reloadData(); reloadData();
(done || noop)();
const isRtl = -1 < inArray(language, ['ar', 'ar_sa', 'he', 'he_he', 'ur', 'ur_ir']); const isRtl = -1 < inArray(language, ['ar', 'ar_sa', 'he', 'he_he', 'ur', 'ur_ir']);
@ -330,14 +318,16 @@ class Translator
// .attr('dir', isRtl ? 'rtl' : 'ltr') // .attr('dir', isRtl ? 'rtl' : 'ltr')
; ;
resolve();
}, 500 < microtime() - start ? 1 : 500); }, 500 < microtime() - start ? 1 : 500);
}) }, () => {
; $html.removeClass('rl-changing-language');
window.rainloopI18N = null;
reject();
});
});
} }
init() { // init section
$html.addClass('rl-' + ($html.attr('dir') || 'ltr')); $html.addClass('rl-' + ($html.attr('dir') || 'ltr'));
}
}
module.exports = new Translator();

View file

@ -20,8 +20,10 @@ const isNull = _.isNull;
const has = _.has; const has = _.has;
const bind = _.bind; const bind = _.bind;
const noop = () => {}; const noop = () => {};
const noopTrue = () => true;
const noopFalse = () => false;
export {trim, inArray, isArray, isObject, isFunc, isUnd, isNull, has, bind, noop, noop as emptyFunction}; export {trim, inArray, isArray, isObject, isFunc, isUnd, isNull, has, bind, noop, noopTrue, noopFalse};
/** /**
* @param {Function} callback * @param {Function} callback

View file

@ -1,5 +1,5 @@
import Translator from 'Common/Translator'; import {i18n} from 'Common/Translator';
import {defautOptionsAfterRender} from 'Common/Utils'; import {defautOptionsAfterRender} from 'Common/Utils';
import {componentExportHelper} from 'Component/Abstract'; import {componentExportHelper} from 'Component/Abstract';
import {AbstractInput} from 'Component/AbstractInput'; import {AbstractInput} from 'Component/AbstractInput';
@ -21,7 +21,7 @@ class SelectComponent extends AbstractInput
if (this.optionsCaption) if (this.optionsCaption)
{ {
this.optionsCaption = Translator.i18n(this.optionsCaption); this.optionsCaption = i18n(this.optionsCaption);
} }
this.defautOptionsAfterRender = defautOptionsAfterRender; this.defautOptionsAfterRender = defautOptionsAfterRender;

View file

@ -75,7 +75,7 @@
if (Utils.isNonEmptyArray(aRoutes)) if (Utils.isNonEmptyArray(aRoutes))
{ {
fMatcher = _.bind(this.onRoute || Utils.emptyFunction, this); fMatcher = _.bind(this.onRoute || Utils.noop, this);
oRoute = crossroads.create(); oRoute = crossroads.create();
_.each(aRoutes, function (aItem) { _.each(aRoutes, function (aItem) {

View file

@ -85,7 +85,7 @@
ComposeAttachmentModel.prototype.CID = ''; ComposeAttachmentModel.prototype.CID = '';
ComposeAttachmentModel.prototype.contentLocation = ''; ComposeAttachmentModel.prototype.contentLocation = '';
ComposeAttachmentModel.prototype.fromMessage = false; ComposeAttachmentModel.prototype.fromMessage = false;
ComposeAttachmentModel.prototype.cancel = Utils.emptyFunction; ComposeAttachmentModel.prototype.cancel = Utils.noop;
/** /**
* @param {AjaxJsonComposeAttachment} oJsonAttachment * @param {AjaxJsonComposeAttachment} oJsonAttachment

View file

@ -194,7 +194,7 @@
if (bUpdate) if (bUpdate)
{ {
require('Remote/User/Ajax').saveSystemFolders(Utils.emptyFunction, { require('Remote/User/Ajax').saveSystemFolders(Utils.noop, {
'SentFolder': FolderStore.sentFolder(), 'SentFolder': FolderStore.sentFolder(),
'DraftFolder': FolderStore.draftFolder(), 'DraftFolder': FolderStore.draftFolder(),
'SpamFolder': FolderStore.spamFolder(), 'SpamFolder': FolderStore.spamFolder(),

View file

@ -113,15 +113,17 @@
self.languageAdminTrigger(Enums.SaveSettingsStep.Animate); self.languageAdminTrigger(Enums.SaveSettingsStep.Animate);
Translator.reload(true, sValue, Translator.reload(true, sValue).then(
fReloadLanguageHelper(Enums.SaveSettingsStep.TrueResult), fReloadLanguageHelper(Enums.SaveSettingsStep.TrueResult),
fReloadLanguageHelper(Enums.SaveSettingsStep.FalseResult)); fReloadLanguageHelper(Enums.SaveSettingsStep.FalseResult)
).then(function() {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'LanguageAdmin': Utils.trim(sValue) 'LanguageAdmin': Utils.trim(sValue)
}); });
}); });
});
self.theme.subscribe(function (sValue) { self.theme.subscribe(function (sValue) {
Utils.changeTheme(sValue, self.themeTrigger); Utils.changeTheme(sValue, self.themeTrigger);

View file

@ -74,7 +74,7 @@
; ;
this.enabledPlugins.subscribe(function (bValue) { this.enabledPlugins.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'EnabledPlugins': bValue ? '1' : '0' 'EnabledPlugins': bValue ? '1' : '0'
}); });
}); });

View file

@ -131,19 +131,19 @@
SecurityAdminSettings.prototype.onBuild = function () SecurityAdminSettings.prototype.onBuild = function ()
{ {
this.capaOpenPGP.subscribe(function (bValue) { this.capaOpenPGP.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'CapaOpenPGP': bValue ? '1' : '0' 'CapaOpenPGP': bValue ? '1' : '0'
}); });
}); });
this.capaTwoFactorAuth.subscribe(function (bValue) { this.capaTwoFactorAuth.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'CapaTwoFactorAuth': bValue ? '1' : '0' 'CapaTwoFactorAuth': bValue ? '1' : '0'
}); });
}); });
this.capaTwoFactorAuthForce.subscribe(function (bValue) { this.capaTwoFactorAuthForce.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'CapaTwoFactorAuthForce': bValue ? '1' : '0' 'CapaTwoFactorAuthForce': bValue ? '1' : '0'
}); });
}); });

View file

@ -79,7 +79,7 @@
self.facebookEnable.subscribe(function (bValue) { self.facebookEnable.subscribe(function (bValue) {
if (self.facebookSupported()) if (self.facebookSupported())
{ {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'FacebookEnable': bValue ? '1' : '0' 'FacebookEnable': bValue ? '1' : '0'
}); });
} }
@ -104,7 +104,7 @@
}); });
self.twitterEnable.subscribe(function (bValue) { self.twitterEnable.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'TwitterEnable': bValue ? '1' : '0' 'TwitterEnable': bValue ? '1' : '0'
}); });
}); });
@ -122,25 +122,25 @@
}); });
self.googleEnable.subscribe(function (bValue) { self.googleEnable.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'GoogleEnable': bValue ? '1' : '0' 'GoogleEnable': bValue ? '1' : '0'
}); });
}); });
self.googleEnableAuth.subscribe(function (bValue) { self.googleEnableAuth.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'GoogleEnableAuth': bValue ? '1' : '0' 'GoogleEnableAuth': bValue ? '1' : '0'
}); });
}); });
self.googleEnableDrive.subscribe(function (bValue) { self.googleEnableDrive.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'GoogleEnableDrive': bValue ? '1' : '0' 'GoogleEnableDrive': bValue ? '1' : '0'
}); });
}); });
self.googleEnablePreview.subscribe(function (bValue) { self.googleEnablePreview.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'GoogleEnablePreview': bValue ? '1' : '0' 'GoogleEnablePreview': bValue ? '1' : '0'
}); });
}); });
@ -164,7 +164,7 @@
}); });
self.dropboxEnable.subscribe(function (bValue) { self.dropboxEnable.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.emptyFunction, { Remote.saveAdminConfig(Utils.noop, {
'DropboxEnable': bValue ? '1' : '0' 'DropboxEnable': bValue ? '1' : '0'
}); });
}); });

View file

@ -169,7 +169,7 @@
FoldersUserSettings.prototype.subscribeFolder = function (oFolder) FoldersUserSettings.prototype.subscribeFolder = function (oFolder)
{ {
Local.set(Enums.ClientSideKeyName.FoldersLashHash, ''); Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
Remote.folderSetSubscribe(Utils.emptyFunction, oFolder.fullNameRaw, true); Remote.folderSetSubscribe(Utils.noop, oFolder.fullNameRaw, true);
oFolder.subScribed(true); oFolder.subScribed(true);
}; };
@ -177,21 +177,21 @@
FoldersUserSettings.prototype.unSubscribeFolder = function (oFolder) FoldersUserSettings.prototype.unSubscribeFolder = function (oFolder)
{ {
Local.set(Enums.ClientSideKeyName.FoldersLashHash, ''); Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
Remote.folderSetSubscribe(Utils.emptyFunction, oFolder.fullNameRaw, false); Remote.folderSetSubscribe(Utils.noop, oFolder.fullNameRaw, false);
oFolder.subScribed(false); oFolder.subScribed(false);
}; };
FoldersUserSettings.prototype.checkableTrueFolder = function (oFolder) FoldersUserSettings.prototype.checkableTrueFolder = function (oFolder)
{ {
Remote.folderSetCheckable(Utils.emptyFunction, oFolder.fullNameRaw, true); Remote.folderSetCheckable(Utils.noop, oFolder.fullNameRaw, true);
oFolder.checkable(true); oFolder.checkable(true);
}; };
FoldersUserSettings.prototype.checkableFalseFolder = function (oFolder) FoldersUserSettings.prototype.checkableFalseFolder = function (oFolder)
{ {
Remote.folderSetCheckable(Utils.emptyFunction, oFolder.fullNameRaw, false); Remote.folderSetCheckable(Utils.noop, oFolder.fullNameRaw, false);
oFolder.checkable(false); oFolder.checkable(false);
}; };

View file

@ -135,15 +135,17 @@
self.languageTrigger(Enums.SaveSettingsStep.Animate); self.languageTrigger(Enums.SaveSettingsStep.Animate);
Translator.reload(false, sValue, Translator.reload(false, sValue).then(
fReloadLanguageHelper(Enums.SaveSettingsStep.TrueResult), fReloadLanguageHelper(Enums.SaveSettingsStep.TrueResult),
fReloadLanguageHelper(Enums.SaveSettingsStep.FalseResult)); fReloadLanguageHelper(Enums.SaveSettingsStep.FalseResult)
).then(function() {
Remote.saveSettings(null, { Remote.saveSettings(null, {
'Language': sValue 'Language': sValue
}); });
}); });
});
self.editorDefaultType.subscribe(function (sValue) { self.editorDefaultType.subscribe(function (sValue) {
Remote.saveSettings(f0, { Remote.saveSettings(f0, {
'EditorDefaultType': sValue 'EditorDefaultType': sValue

View file

@ -3,30 +3,27 @@ import {_} from 'common';
import {CookieDriver} from 'Common/ClientStorageDriver/Cookie'; import {CookieDriver} from 'Common/ClientStorageDriver/Cookie';
import {LocalStorageDriver} from 'Common/ClientStorageDriver/LocalStorage'; import {LocalStorageDriver} from 'Common/ClientStorageDriver/LocalStorage';
class ClientStorage const SupportedStorageDriver = _.find(
{ [LocalStorageDriver, CookieDriver], (StorageDriver) => StorageDriver && StorageDriver.supported()
constructor() { );
const SupportedStorageDriver = _.find([LocalStorageDriver, CookieDriver],
(StorageDriver) => StorageDriver && StorageDriver.supported()); const driver = SupportedStorageDriver ? new SupportedStorageDriver() : null;
this.driver = SupportedStorageDriver ? new SupportedStorageDriver() : null;
}
/** /**
* @param {number} key * @param {number} key
* @param {*} data * @param {*} data
* @return {boolean} * @return {boolean}
*/ */
set(key, data) { export function set(key, data)
return this.driver ? this.driver.set('p' + key, data) : false; {
return driver ? driver.set('p' + key, data) : false;
} }
/** /**
* @param {number} key * @param {number} key
* @return {*} * @return {*}
*/ */
get(key) { export function get(key)
return this.driver ? this.driver.get('p' + key) : null; {
return driver ? driver.get('p' + key) : null;
} }
}
module.exports = new ClientStorage();

View file

@ -1,105 +1,90 @@
import window from 'window'; import window from 'window';
import JSON from 'JSON';
const const STORAGE_KEY = '__rlA';
STORAGE_KEY = '__rlA', const TIME_KEY = '__rlT';
TIME_KEY = '__rlT'
;
class RainLoopStorage const SESS_STORAGE = window.sessionStorage || null;
{ const WIN_STORAGE = window.top || window || null;
s = null;
t = null;
constructor() const __get = (key) => {
{
this.s = window.sessionStorage || null;
this.t = window.top || window;
this.init();
}
__get(key) {
let result = null; let result = null;
if (this.s) if (SESS_STORAGE)
{ {
result = this.s.getItem(key) || null; result = SESS_STORAGE.getItem(key) || null;
} }
else if (this.t && JSON) else if (WIN_STORAGE && JSON)
{ {
const data = this.t.name && '{' === this.t.name.toString().substr(0, 1) ? JSON.parse(this.t.name.toString()) : null; const data = WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1) ? JSON.parse(WIN_STORAGE.name.toString()) : null;
result = data ? (data[key] || null) : null; result = data ? (data[key] || null) : null;
} }
return result; return result;
} };
__set(key, value) { const __set = (key, value) => {
if (this.s)
if (SESS_STORAGE)
{ {
this.s.setItem(key, value); SESS_STORAGE.setItem(key, value);
} }
else if (this.t && JSON) else if (WIN_STORAGE && JSON)
{ {
let data = this.t.name && '{' === this.t.name.toString().substr(0, 1) ? JSON.parse(this.t.name.toString()) : null; let data = WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1) ? JSON.parse(WIN_STORAGE.name.toString()) : null;
data = data || {}; data = data || {};
data[key] = value; data[key] = value;
this.t.name = JSON.stringify(data); WIN_STORAGE.name = JSON.stringify(data);
}
} }
};
timestamp() { const timestamp = () => window.Math.round((new window.Date()).getTime() / 1000);
return window.Math.round((new Date()).getTime() / 1000);
}
checkTimestamp() { const setTimestamp = () => __set(TIME_KEY, timestamp());
if (this.timestamp() > this.getTimestamp() + 1000 * 60 * 60) // 60m const getTimestamp = () => {
let time = __get(TIME_KEY, 0);
return time ? (window.parseInt(time, 10) || 0) : 0;
};
/**
* @return {string}
*/
export function getHash()
{ {
this.clearHash(); return __get(STORAGE_KEY);
return true;
} }
return false; export function setHash()
} {
init() {
window.setInterval(() => {
this.setTimestamp();
}, 1000 * 60); // 1m
}
getHash() {
return this.__get(STORAGE_KEY);
}
setHash() {
const const
key = 'AuthAccountHash', key = 'AuthAccountHash',
appData = window.__rlah_data() appData = window.__rlah_data()
; ;
this.__set(STORAGE_KEY, appData && appData[key] ? appData[key] : ''); __set(STORAGE_KEY, appData && appData[key] ? appData[key] : '');
this.setTimestamp(); setTimestamp();
} }
export function clearHash()
setTimestamp() { {
this.__set(TIME_KEY, this.timestamp()); __set(STORAGE_KEY, '');
setTimestamp();
} }
getTimestamp() { export function checkTimestamp()
let time = this.__get(TIME_KEY, 0); {
return time ? (window.parseInt(time, 10) | 0) : 0; if (timestamp() > getTimestamp() + 1000 * 60 * 60) // 60m
{
clearHash();
return true;
}
return false;
} }
clearHash() { // init section
this.__set(STORAGE_KEY, ''); window.setInterval(() => {
this.setTimestamp(); setTimestamp();
} }, 1000 * 60); // 1m
}
module.exports = new RainLoopStorage();

View file

@ -20,10 +20,14 @@
this.languagesAdmin = ko.observableArray([]); this.languagesAdmin = ko.observableArray([]);
this.language = ko.observable('') this.language = ko.observable('')
.extend({'limitedList': this.languages}); .extend({'limitedList': this.languages})
.extend({'reversible': true})
;
this.languageAdmin = ko.observable('') this.languageAdmin = ko.observable('')
.extend({'limitedList': this.languagesAdmin}); .extend({'limitedList': this.languagesAdmin})
.extend({'reversible': true})
;
this.userLanguage = ko.observable(''); this.userLanguage = ko.observable('');
this.userLanguageAdmin = ko.observable(''); this.userLanguageAdmin = ko.observable('');

View file

@ -62,7 +62,7 @@
Settings.settingsSet('TrashFolder', FolderStore.trashFolder()); Settings.settingsSet('TrashFolder', FolderStore.trashFolder());
Settings.settingsSet('ArchiveFolder', FolderStore.archiveFolder()); Settings.settingsSet('ArchiveFolder', FolderStore.archiveFolder());
Remote.saveSystemFolders(Utils.emptyFunction, { Remote.saveSystemFolders(Utils.noop, {
'SentFolder': FolderStore.sentFolder(), 'SentFolder': FolderStore.sentFolder(),
'DraftFolder': FolderStore.draftFolder(), 'DraftFolder': FolderStore.draftFolder(),
'SpamFolder': FolderStore.spamFolder(), 'SpamFolder': FolderStore.spamFolder(),

View file

@ -469,11 +469,12 @@
} }
_.delay(function () { _.delay(function () {
LanguageStore.language.subscribe(function (sValue) { LanguageStore.language.subscribe(function (sValue) {
self.langRequest(true); self.langRequest(true);
Translator.reload(false, sValue, function() { Translator.reload(false, sValue).then(function() {
self.langRequest(false); self.langRequest(false);
self.bSendLanguage = true; self.bSendLanguage = true;
}, function() { }, function() {
@ -481,6 +482,7 @@
}); });
}); });
}, 50); }, 50);
Utils.triggerAutocompleteInputChange(true); Utils.triggerAutocompleteInputChange(true);

View file

@ -258,7 +258,7 @@
MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), true); MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), true);
}, this.canBeMoved); }, this.canBeMoved);
this.moveCommand = Utils.createCommand(this, Utils.emptyFunction, this.canBeMoved); this.moveCommand = Utils.createCommand(this, Utils.noop, this.canBeMoved);
this.reloadCommand = Utils.createCommand(this, function () { this.reloadCommand = Utils.createCommand(this, function () {
if (!MessageStore.messageListCompleteLoadingThrottleForAnimation() && this.allowReload) if (!MessageStore.messageListCompleteLoadingThrottleForAnimation() && this.allowReload)
@ -558,7 +558,7 @@
Cache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw); Cache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw);
} }
Remote.messageSetSeenToAll(Utils.emptyFunction, sFolderFullNameRaw, true); Remote.messageSetSeenToAll(Utils.noop, sFolderFullNameRaw, true);
break; break;
case Enums.MessageSetAction.UnsetSeen: case Enums.MessageSetAction.UnsetSeen:
oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw); oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
@ -571,7 +571,7 @@
oFolder.messageCountUnread(oFolder.messageCountAll()); oFolder.messageCountUnread(oFolder.messageCountAll());
Cache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw); Cache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw);
} }
Remote.messageSetSeenToAll(Utils.emptyFunction, sFolderFullNameRaw, false); Remote.messageSetSeenToAll(Utils.noop, sFolderFullNameRaw, false);
break; break;
} }
@ -784,11 +784,6 @@
{ {
var self = this; var self = this;
// disable print
key('ctrl+p, command+p', Enums.KeyState.MessageList, function () {
return false;
});
key('enter', Enums.KeyState.MessageList, function () { key('enter', Enums.KeyState.MessageList, function () {
if (self.message() && self.useAutoSelect()) if (self.message() && self.useAutoSelect())
{ {

View file

@ -186,7 +186,7 @@
Local.set(Enums.ClientSideKeyName.LastReplyAction, sValue); Local.set(Enums.ClientSideKeyName.LastReplyAction, sValue);
}); });
this.showFullInfo = ko.observable(false); this.showFullInfo = ko.observable('1' === Local.get(Enums.ClientSideKeyName.MessageHeaderFullInfo));
this.moreDropdownTrigger = ko.observable(false); this.moreDropdownTrigger = ko.observable(false);
this.messageDomFocused = ko.observable(false).extend({'rateLimit': 0}); this.messageDomFocused = ko.observable(false).extend({'rateLimit': 0});
@ -217,7 +217,7 @@
this.forwardAsAttachmentCommand = createCommandHelper(Enums.ComposeType.ForwardAsAttachment); this.forwardAsAttachmentCommand = createCommandHelper(Enums.ComposeType.ForwardAsAttachment);
this.editAsNewCommand = createCommandHelper(Enums.ComposeType.EditAsNew); this.editAsNewCommand = createCommandHelper(Enums.ComposeType.EditAsNew);
this.messageVisibilityCommand = Utils.createCommand(this, Utils.emptyFunction, this.messageVisibility); this.messageVisibilityCommand = Utils.createCommand(this, Utils.noop, this.messageVisibility);
this.messageEditCommand = Utils.createCommand(this, function () { this.messageEditCommand = Utils.createCommand(this, function () {
this.editMessage(); this.editMessage();
@ -672,9 +672,10 @@
_.delay(fCheckHeaderHeight, 500); _.delay(fCheckHeaderHeight, 500);
}, 50)); }, 50));
this.showFullInfo.subscribe(function () { this.showFullInfo.subscribe(function (value) {
Utils.windowResize(); Utils.windowResize();
Utils.windowResize(250); Utils.windowResize(250);
Local.set(Enums.ClientSideKeyName.MessageHeaderFullInfo, value ? '1' : '0');
}); });
if (this.dropboxEnabled() && this.dropboxApiKey() && !window.Dropbox) if (this.dropboxEnabled() && this.dropboxApiKey() && !window.Dropbox)
@ -873,13 +874,13 @@
}); });
// message information // message information
// key('i', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () { key('ctrl+i, command+i', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
// if (MessageStore.message()) if (MessageStore.message())
// { {
// self.showFullInfo(!self.showFullInfo()); self.showFullInfo(!self.showFullInfo());
// return false; }
// } return false;
// }); });
// toggle message blockquotes // toggle message blockquotes
key('b', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () { key('b', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
@ -901,7 +902,7 @@
}); });
// print // print
key('ctrl+p, command+p', Enums.KeyState.MessageView, function () { key('ctrl+p, command+p', [Enums.KeyState.MessageView, Enums.KeyState.MessageList], function () {
if (self.message()) if (self.message())
{ {
self.message().printMessage(); self.message().printMessage();
@ -1199,7 +1200,7 @@
{ {
if (oMessage && '' !== oMessage.readReceipt()) if (oMessage && '' !== oMessage.readReceipt())
{ {
Remote.sendReadReceiptMessage(Utils.emptyFunction, oMessage.folderFullNameRaw, oMessage.uid, Remote.sendReadReceiptMessage(Utils.noop, oMessage.folderFullNameRaw, oMessage.uid,
oMessage.readReceipt(), oMessage.readReceipt(),
Translator.i18n('READ_RECEIPT/SUBJECT', {'SUBJECT': oMessage.subject()}), Translator.i18n('READ_RECEIPT/SUBJECT', {'SUBJECT': oMessage.subject()}),
Translator.i18n('READ_RECEIPT/BODY', {'READ-RECEIPT': AccountStore.email()})); Translator.i18n('READ_RECEIPT/BODY', {'READ-RECEIPT': AccountStore.email()}));

View file

@ -5,7 +5,7 @@ import {kill_CtrlA_CtrlS, detectDropdownVisibility, createCommand} from 'Common/
import {$win, $html, data as GlobalsData, bMobileDevice} from 'Common/Globals'; import {$win, $html, data as GlobalsData, bMobileDevice} from 'Common/Globals';
import * as Enums from 'Common/Enums'; import * as Enums from 'Common/Enums';
import * as Plugins from 'Common/Plugins'; import * as Plugins from 'Common/Plugins';
import Translator from 'Common/Translator'; import {i18n} from 'Common/Translator';
import EmailModel from 'Model/Email'; import EmailModel from 'Model/Email';
export default (App) => { export default (App) => {
@ -28,7 +28,7 @@ export default (App) => {
const rl = window.rl || {}; const rl = window.rl || {};
rl.i18n = Translator.i18n; rl.i18n = i18n;
rl.createCommand = createCommand; rl.createCommand = createCommand;
rl.addSettingsViewModel = Plugins.addSettingsViewModel; rl.addSettingsViewModel = Plugins.addSettingsViewModel;

23
jsconfig.json Normal file
View file

@ -0,0 +1,23 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=759670
// for the documentation about the jsconfig.json format
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"allowSyntheticDefaultImports": true
},
"exclude": [
"build",
"data",
"vendors",
"rainloop",
"plugins",
"node_modules",
"bower_components",
"jspm_packages",
"nbproject",
"tests",
"tmp",
"temp"
]
}