import window from 'window'; import $ from '$'; import _ from '_'; import ko from 'ko'; import {$win, $div, dropdownVisibility, data as GlobalsData} from 'Common/Globals'; import {ComposeType, EventKeyCode, SaveSettingsStep, FolderType} from 'Common/Enums'; import {Mime} from 'Common/Mime'; import {jassl} from 'Common/Jassl'; import Autolinker from 'Autolinker'; const trim = $.trim; const inArray = $.inArray; const isArray = _.isArray; const isObject = _.isObject; const isFunc = _.isFunction; const isUnd = _.isUndefined; const isNull = _.isNull; const has = _.has; const bind = _.bind; const noop = () => {}; // eslint-disable-line no-empty-function const noopTrue = () => true; const noopFalse = () => false; export {trim, inArray, isArray, isObject, isFunc, isUnd, isNull, has, bind, noop, noopTrue, noopFalse, jassl}; /** * @param {Function} func */ export function silentTryCatch(func) { try { func(); } catch (e) {} // eslint-disable-line no-empty } /** * @param {*} value * @returns {boolean} */ export function isNormal(value) { return !isUnd(value) && !isNull(value); } /** * @param {(string|number)} value * @param {boolean=} includeZero = true * @returns {boolean} */ export function isPosNumeric(value, includeZero = true) { return !isNormal(value) ? false : (includeZero ? (/^[0-9]*$/).test(value.toString()) : (/^[1-9]+[0-9]*$/).test(value.toString())); } /** * @param {*} value * @param {number=} defaultValur = 0 * @returns {number} */ export function pInt(value, defaultValur = 0) { const result = isNormal(value) && '' !== value ? window.parseInt(value, 10) : defaultValur; return window.isNaN(result) ? defaultValur : result; } /** * @param {*} value * @returns {string} */ export function pString(value) { return isNormal(value) ? '' + value : ''; } /** * @param {*} value * @returns {boolean} */ export function pBool(value) { return !!value; } /** * @param {*} value * @returns {string} */ export function boolToAjax(value) { return value ? '1' : '0'; } /** * @param {*} values * @returns {boolean} */ export function isNonEmptyArray(values) { return isArray(values) && 0 < values.length; } /** * @param {string} component * @returns {string} */ export function encodeURIComponent(component) { return window.encodeURIComponent(component); } /** * @param {string} component * @returns {string} */ export function decodeURIComponent(component) { return window.decodeURIComponent(component); } /** * @param {string} url * @returns {string} */ export function decodeURI(url) { return window.decodeURI(url); } /** * @param {string} url * @returns {string} */ export function encodeURI(url) { return window.encodeURI(url); } /** * @param {string} queryString * @returns {Object} */ export function simpleQueryParser(queryString) { let index = 0, len = 0, temp = null; const queries = queryString.split('&'), params = {}; for (len = queries.length; index < len; index++) { temp = queries[index].split('='); params[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]); } return params; } /** * @param {number=} len = 32 * @returns {string} */ export function fakeMd5(len = 32) { const line = '0123456789abcdefghijklmnopqrstuvwxyz', lineLen = line.length; len = pInt(len); let result = ''; while (result.length < len) { result += line.substr(window.Math.round(window.Math.random() * lineLen), 1); } return result; } /** * @param {string} text * @returns {string} */ export function encodeHtml(text) { return isNormal(text) ? _.escape(text.toString()) : ''; } /** * @param {string} text * @param {number=} len = 100 * @returns {string} */ export function splitPlainText(text, len = 100) { let prefix = '', subText = '', result = text, spacePos = 0, newLinePos = 0; while (result.length > len) { subText = result.substring(0, len); spacePos = subText.lastIndexOf(' '); newLinePos = subText.lastIndexOf('\n'); if (-1 !== newLinePos) { spacePos = newLinePos; } if (-1 === spacePos) { spacePos = len; } prefix += subText.substring(0, spacePos) + '\n'; result = result.substring(spacePos + 1); } return prefix + result; } const timeOutAction = (function() { const timeOuts = {}; return (action, fFunction, timeOut) => { timeOuts[action] = isUnd(timeOuts[action]) ? 0 : timeOuts[action]; window.clearTimeout(timeOuts[action]); timeOuts[action] = window.setTimeout(fFunction, timeOut); }; }()); const timeOutActionSecond = (function() { const timeOuts = {}; return (action, fFunction, timeOut) => { if (!timeOuts[action]) { timeOuts[action] = window.setTimeout(() => { fFunction(); timeOuts[action] = 0; }, timeOut); } }; }()); export {timeOutAction, timeOutActionSecond}; /** * @returns {boolean} */ export function inFocus() { try { if (window.document.activeElement) { if (isUnd(window.document.activeElement.__inFocusCache)) { window.document.activeElement.__inFocusCache = $(window.document.activeElement).is('input,textarea,iframe,.cke_editable'); } return !!window.document.activeElement.__inFocusCache; } } catch (e) {} // eslint-disable-line no-empty return false; } /** * @param {boolean} force * @returns {void} */ export function removeInFocus(force) { if (window.document && window.document.activeElement && window.document.activeElement.blur) { try { const activeEl = $(window.document.activeElement); if (activeEl && activeEl.is('input,textarea')) { window.document.activeElement.blur(); } else if (force) { window.document.activeElement.blur(); } } catch (e) {} // eslint-disable-line no-empty } } /** * @returns {void} */ export function removeSelection() { try { if (window && window.getSelection) { const sel = window.getSelection(); if (sel && sel.removeAllRanges) { sel.removeAllRanges(); } } else if (window.document && window.document.selection && window.document.selection.empty) { window.document.selection.empty(); } } catch (e) {} // eslint-disable-line no-empty } /** * @param {string} prefix * @param {string} subject * @returns {string} */ export function replySubjectAdd(prefix, subject) { prefix = trim(prefix.toUpperCase()); subject = trim(subject.replace(/[\s]+/g, ' ')); let drop = false, re = 'RE' === prefix, fwd = 'FWD' === prefix; const parts = [], prefixIsRe = !fwd; if ('' !== subject) { _.each(subject.split(':'), (part) => { const trimmedPart = trim(part); if (!drop && ((/^(RE|FWD)$/i).test(trimmedPart) || (/^(RE|FWD)[\[\(][\d]+[\]\)]$/i).test(trimmedPart))) { if (!re) { re = !!(/^RE/i).test(trimmedPart); } if (!fwd) { fwd = !!(/^FWD/i).test(trimmedPart); } } else { parts.push(part); drop = true; } }); } if (prefixIsRe) { re = false; } else { fwd = false; } return trim( (prefixIsRe ? 'Re: ' : 'Fwd: ') + (re ? 'Re: ' : '') + (fwd ? 'Fwd: ' : '') + trim(parts.join(':')) ); } /** * @param {number} num * @param {number} dec * @returns {number} */ export function roundNumber(num, dec) { return window.Math.round(num * window.Math.pow(10, dec)) / window.Math.pow(10, dec); } /** * @param {(number|string)} sizeInBytes * @returns {string} */ export function friendlySize(sizeInBytes) { sizeInBytes = pInt(sizeInBytes); switch (true) { case 1073741824 <= sizeInBytes: return roundNumber(sizeInBytes / 1073741824, 1) + 'GB'; case 1048576 <= sizeInBytes: return roundNumber(sizeInBytes / 1048576, 1) + 'MB'; case 1024 <= sizeInBytes: return roundNumber(sizeInBytes / 1024, 0) + 'KB'; // no default } return sizeInBytes + 'B'; } /** * @param {string} desc */ export function log(desc) { if (window.console && window.console.log) { window.console.log(desc); } } /** * @param {?} object * @param {string} methodName * @param {Array=} params * @param {number=} delay = 0 */ export function delegateRun(object, methodName, params, delay = 0) { if (object && object[methodName]) { delay = pInt(delay); params = isArray(params) ? params : []; if (0 >= delay) { object[methodName](...params); } else { _.delay(() => { object[methodName](...params); }, delay); } } } /** * @param {?} event */ export function killCtrlACtrlS(event) { event = event || window.event; if (event && event.ctrlKey && !event.shiftKey && !event.altKey) { const key = event.keyCode || event.which; if (key === EventKeyCode.S) { event.preventDefault(); return; } else if (key === EventKeyCode.A) { const sender = event.target || event.srcElement; if (sender && ('true' === '' + sender.contentEditable || (sender.tagName && sender.tagName.match(/INPUT|TEXTAREA/i)))) { return; } if (window.getSelection) { window.getSelection().removeAllRanges(); } else if (window.document.selection && window.document.selection.clear) { window.document.selection.clear(); } event.preventDefault(); } } } /** * @param {(Object|null|undefined)} context * @param {Function} fExecute * @param {(Function|boolean|null)=} fCanExecute = true * @returns {Function} */ export function createCommandLegacy(context, fExecute, fCanExecute = true) { let fResult = null; const fNonEmpty = (...args) => { if (fResult && fResult.canExecute && fResult.canExecute()) { fExecute.apply(context, args); } return false; }; fResult = fExecute ? fNonEmpty : noop; fResult.enabled = ko.observable(true); if (isFunc(fCanExecute)) { fResult.canExecute = ko.computed(() => fResult.enabled() && fCanExecute.call(context)); } else { fResult.canExecute = ko.computed(() => fResult.enabled() && !!fCanExecute); } return fResult; } /** * @param {Function} fExecute * @param {(Function|boolean|null)=} fCanExecute = true * @returns {Function} */ export function createCommand(fExecute, fCanExecute = true) { return createCommandLegacy(null, fExecute, fCanExecute); } /** * @param {string} theme * @returns {string} */ export const convertThemeName = _.memoize((theme) => { if ('@custom' === theme.substr(-7)) { theme = trim(theme.substring(0, theme.length - 7)); } return trim(theme.replace(/[^a-zA-Z0-9]+/g, ' ').replace(/([A-Z])/g, ' $1').replace(/[\s]+/g, ' ')); }); /** * @param {string} name * @returns {string} */ export function quoteName(name) { return name.replace(/["]/g, '\\"'); } /** * @returns {number} */ export function microtime() { return (new window.Date()).getTime(); } /** * @returns {number} */ export function timestamp() { return window.Math.round(microtime() / 1000); } /** * * @param {string} language * @param {boolean=} isEng = false * @returns {string} */ export function convertLangName(language, isEng = false) { return require('Common/Translator').i18n('LANGS_NAMES' + (true === isEng ? '_EN' : '') + '/LANG_' + language.toUpperCase().replace(/[^a-zA-Z0-9]+/g, '_'), null, language); } /** * @returns {object} */ export function draggablePlace() { return $('
]*><\/p>/gi, '') .replace(/
]*>([\s\S\r\n\t]*)<\/pre>/gmi, convertPre) .replace(/[\s]+/gm, ' ') .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue) .replace(/
]*>/gmi, '\n') .replace(/<\/h[\d]>/gi, '\n') .replace(/<\/p>/gi, '\n\n') .replace(/
]*>/gmi, '\n__bq__start__\n') .replace(/<\/blockquote>/gmi, '\n__bq__end__\n') .replace(/]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks) .replace(/<\/div>/gi, '\n') .replace(/ /gi, ' ') .replace(/"/gi, '"') .replace(/<[^>]*>/gm, ''); text = $div.html(text).text(); text = text .replace(/\n[ \t]+/gm, '\n') .replace(/[\n]{3,}/gm, '\n\n') .replace(/>/gi, '>') .replace(/</gi, '<') .replace(/&/gi, '&'); text = splitPlainText(trim(text)); pos = 0; limit = 800; while (0 < limit) { limit -= 1; iP1 = text.indexOf('__bq__start__', pos); if (-1 < iP1) { iP2 = text.indexOf('__bq__start__', iP1 + 5); iP3 = text.indexOf('__bq__end__', iP1 + 5); if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3) { text = text.substring(0, iP1) + convertBlockquote(text.substring(iP1 + 13, iP3)) + text.substring(iP3 + 11); pos = 0; } else if (-1 < iP2 && iP2 < iP3) { pos = iP2 - 1; } else { pos = 0; } } else { break; } } text = text .replace(/__bq__start__/gm, '') .replace(/__bq__end__/gm, ''); return text; } /** * @param {string} plain * @param {boolean} findEmailAndLinksInText = false * @returns {string} */ export function plainToHtml(plain, findEmailAndLinksInText = false) { plain = plain.toString().replace(/\r/g, ''); plain = plain.replace(/^>[> ]>+/gm, ([match]) => (match ? match.replace(/[ ]+/g, '') : match)); let bIn = false, bDo = true, bStart = true, aNextText = [], sLine = '', iIndex = 0, aText = plain.split('\n'); do { bDo = false; aNextText = []; for (iIndex = 0; iIndex < aText.length; iIndex++) { sLine = aText[iIndex]; bStart = '>' === sLine.substr(0, 1); if (bStart && !bIn) { bDo = true; bIn = true; aNextText.push('~~~blockquote~~~'); aNextText.push(sLine.substr(1)); } else if (!bStart && bIn) { if ('' !== sLine) { bIn = false; aNextText.push('~~~/blockquote~~~'); aNextText.push(sLine); } else { aNextText.push(sLine); } } else if (bStart && bIn) { aNextText.push(sLine.substr(1)); } else { aNextText.push(sLine); } } if (bIn) { bIn = false; aNextText.push('~~~/blockquote~~~'); } aText = aNextText; } while (bDo); plain = aText.join('\n'); plain = plain // .replace(/~~~\/blockquote~~~\n~~~blockquote~~~/g, '\n') .replace(/&/g, '&') .replace(/>/g, '>').replace(/') .replace(/[\s]*~~~\/blockquote~~~/g, '') .replace(/\n/g, '