UNPKG

@corpecca/qp-web-resources

Version:
946 lines (733 loc) 29.4 kB
(function (define) { define(['jquery'], function ($) { return (function () { var qp = window.qp || {}; /* Application paths *****************************************/ //Current application root path (including virtual directory if exists). qp.appPath = qp.appPath || '/'; qp.pageLoadTime = new Date(); //Converts given path to absolute path using qp.appPath variable. qp.toAbsAppPath = function (path) { if (path.indexOf('/') == 0) { path = path.substring(1); } return qp.appPath + path; }; /* MULTITENANCY */ qp.multiTenancy = qp.multiTenancy || {}; qp.multiTenancy.isEnabled = false; qp.multiTenancy.ignoreFeatureCheckForHostUsers = false; qp.multiTenancy.sides = { TENANT: 1, HOST: 2 }; qp.multiTenancy.tenantIdCookieName = 'Qp.TenantId'; qp.multiTenancy.setTenantIdCookie = function (tenantId) { if (tenantId) { qp.utils.setCookieValue( qp.multiTenancy.tenantIdCookieName, tenantId.toString(), new Date(new Date().getTime() + 5 * 365 * 86400000), //5 years qp.appPath, qp.domain ); } else { qp.utils.deleteCookie(qp.multiTenancy.tenantIdCookieName, qp.appPath); } }; qp.multiTenancy.getTenantIdCookie = function () { var value = qp.utils.getCookieValue(qp.multiTenancy.tenantIdCookieName); if (!value) { return null; } return parseInt(value); } /* SESSION */ qp.session = qp.session || { multiTenancySide: qp.multiTenancy.sides.HOST }; /* LOCALIZATION ***********************************************/ //Implements Localization API that simplifies usage of localization scripts generated by Qp. qp.localization = qp.localization || {}; qp.localization.languages = []; qp.localization.currentLanguage = {}; qp.localization.sources = []; qp.localization.values = {}; qp.localization.localize = function (key, sourceName) { sourceName = sourceName || qp.localization.defaultSourceName; var source = qp.localization.values[sourceName]; if (!source) { qp.log.warn('Could not find localization source: ' + sourceName); return key; } var value = source[key]; if (value == undefined) { return key; } var copiedArguments = Array.prototype.slice.call(arguments, 0); copiedArguments.splice(1, 1); copiedArguments[0] = value; return qp.utils.formatString.apply(this, copiedArguments); }; qp.localization.getSource = function (sourceName) { return function (key) { var copiedArguments = Array.prototype.slice.call(arguments, 0); copiedArguments.splice(1, 0, sourceName); return qp.localization.localize.apply(this, copiedArguments); }; }; qp.localization.isCurrentCulture = function (name) { return qp.localization.currentCulture && qp.localization.currentCulture.name && qp.localization.currentCulture.name.indexOf(name) == 0; }; qp.localization.defaultSourceName = undefined; qp.localization.qpWeb = qp.localization.getSource('QpWeb'); /* AUTHORIZATION **********************************************/ //Implements Authorization API that simplifies usage of authorization scripts generated by Qp. qp.auth = qp.auth || {}; qp.auth.allPermissions = qp.auth.allPermissions || {}; qp.auth.grantedPermissions = qp.auth.grantedPermissions || {}; //Deprecated. Use qp.auth.isGranted instead. qp.auth.hasPermission = function (permissionName) { return qp.auth.isGranted.apply(this, arguments); }; //Deprecated. Use qp.auth.isAnyGranted instead. qp.auth.hasAnyOfPermissions = function () { return qp.auth.isAnyGranted.apply(this, arguments); }; //Deprecated. Use qp.auth.areAllGranted instead. qp.auth.hasAllOfPermissions = function () { return qp.auth.areAllGranted.apply(this, arguments); }; qp.auth.isGranted = function (permissionName) { return qp.auth.allPermissions[permissionName] != undefined && qp.auth.grantedPermissions[permissionName] != undefined; }; qp.auth.isAnyGranted = function () { if (!arguments || arguments.length <= 0) { return true; } for (var i = 0; i < arguments.length; i++) { if (qp.auth.isGranted(arguments[i])) { return true; } } return false; }; qp.auth.areAllGranted = function () { if (!arguments || arguments.length <= 0) { return true; } for (var i = 0; i < arguments.length; i++) { if (!qp.auth.isGranted(arguments[i])) { return false; } } return true; }; qp.auth.tokenCookieName = 'Qp.AuthToken'; qp.auth.setToken = function (authToken, expireDate) { qp.utils.setCookieValue(qp.auth.tokenCookieName, authToken, expireDate, qp.appPath, qp.domain); }; qp.auth.getToken = function() { return qp.utils.getCookieValue(qp.auth.tokenCookieName); }; qp.auth.clearToken = function() { qp.auth.setToken(); }; qp.auth.refreshTokenCookieName = 'Qp.AuthRefreshToken'; qp.auth.setRefreshToken = function (refreshToken, expireDate) { qp.utils.setCookieValue(qp.auth.refreshTokenCookieName, refreshToken, expireDate, qp.appPath, qp.domain); }; qp.auth.getRefreshToken = function() { return qp.utils.getCookieValue(qp.auth.refreshTokenCookieName); }; qp.auth.clearRefreshToken = function() { qp.auth.setRefreshToken(); }; /* FEATURE SYSTEM *********************************************/ //Implements Features API that simplifies usage of feature scripts generated by Qp. qp.features = qp.features || {}; qp.features.allFeatures = qp.features.allFeatures || {}; qp.features.get = function (name) { return qp.features.allFeatures[name]; } qp.features.getValue = function (name) { var feature = qp.features.get(name); if (feature == undefined) { return undefined; } return feature.value; } qp.features.isEnabled = function (name) { var value = qp.features.getValue(name); return value == 'true' || value == 'True'; } /* SETTINGS **************************************************/ //Implements Settings API that simplifies usage of setting scripts generated by Qp. qp.setting = qp.setting || {}; qp.setting.values = qp.setting.values || {}; qp.setting.get = function (name) { return qp.setting.values[name]; }; qp.setting.getBoolean = function (name) { var value = qp.setting.get(name); return value == 'true' || value == 'True'; }; qp.setting.getInt = function (name) { return parseInt(qp.setting.values[name]); }; /* REALTIME NOTIFICATIONS ************************************/ qp.notifications = qp.notifications || {}; qp.notifications.severity = { INFO: 0, SUCCESS: 1, WARN: 2, ERROR: 3, FATAL: 4 }; qp.notifications.userNotificationState = { UNREAD: 0, READ: 1 }; qp.notifications.getUserNotificationStateAsString = function (userNotificationState) { switch (userNotificationState) { case qp.notifications.userNotificationState.READ: return 'READ'; case qp.notifications.userNotificationState.UNREAD: return 'UNREAD'; default: qp.log.warn('Unknown user notification state value: ' + userNotificationState) return '?'; } }; qp.notifications.getUiNotifyFuncBySeverity = function (severity) { switch (severity) { case qp.notifications.severity.SUCCESS: return qp.notify.success; case qp.notifications.severity.WARN: return qp.notify.warn; case qp.notifications.severity.ERROR: return qp.notify.error; case qp.notifications.severity.FATAL: return qp.notify.error; case qp.notifications.severity.INFO: default: return qp.notify.info; } }; qp.notifications.messageFormatters = {}; qp.notifications.messageFormatters['Qp.Notifications.MessageNotificationData'] = function (userNotification) { return userNotification.notification.data.message || userNotification.notification.data.properties.Message; }; qp.notifications.messageFormatters['Qp.Notifications.LocalizableMessageNotificationData'] = function (userNotification) { var message = userNotification.notification.data.message || userNotification.notification.data.properties.Message; var localizedMessage = qp.localization.localize( message.name, message.sourceName ); if (userNotification.notification.data.properties) { if ($) { //Prefer to use jQuery if possible $.each(userNotification.notification.data.properties, function (key, value) { localizedMessage = localizedMessage.replace('{' + key + '}', value); }); } else { //alternative for $.each var properties = Object.keys(userNotification.notification.data.properties); for (var i = 0; i < properties.length; i++) { localizedMessage = localizedMessage.replace('{' + properties[i] + '}', userNotification.notification.data.properties[properties[i]]); } } } return localizedMessage; }; qp.notifications.getFormattedMessageFromUserNotification = function (userNotification) { var formatter = qp.notifications.messageFormatters[userNotification.notification.data.type]; if (!formatter) { qp.log.warn('No message formatter defined for given data type: ' + userNotification.notification.data.type) return '?'; } if (!qp.utils.isFunction(formatter)) { qp.log.warn('Message formatter should be a function! It is invalid for data type: ' + userNotification.notification.data.type) return '?'; } return formatter(userNotification); } qp.notifications.showUiNotifyForUserNotification = function (userNotification, options) { var message = qp.notifications.getFormattedMessageFromUserNotification(userNotification); var uiNotifyFunc = qp.notifications.getUiNotifyFuncBySeverity(userNotification.notification.severity); uiNotifyFunc(message, undefined, options); } /* LOGGING ***************************************************/ //Implements Logging API that provides secure & controlled usage of console.log qp.log = qp.log || {}; qp.log.levels = { DEBUG: 1, INFO: 2, WARN: 3, ERROR: 4, FATAL: 5 }; qp.log.level = qp.log.levels.DEBUG; qp.log.log = function (logObject, logLevel) { if (!window.console || !window.console.log) { return; } if (logLevel != undefined && logLevel < qp.log.level) { return; } console.log(logObject); }; qp.log.debug = function (logObject) { qp.log.log("DEBUG: ", qp.log.levels.DEBUG); qp.log.log(logObject, qp.log.levels.DEBUG); }; qp.log.info = function (logObject) { qp.log.log("INFO: ", qp.log.levels.INFO); qp.log.log(logObject, qp.log.levels.INFO); }; qp.log.warn = function (logObject) { qp.log.log("WARN: ", qp.log.levels.WARN); qp.log.log(logObject, qp.log.levels.WARN); }; qp.log.error = function (logObject) { qp.log.log("ERROR: ", qp.log.levels.ERROR); qp.log.log(logObject, qp.log.levels.ERROR); }; qp.log.fatal = function (logObject) { qp.log.log("FATAL: ", qp.log.levels.FATAL); qp.log.log(logObject, qp.log.levels.FATAL); }; /* NOTIFICATION *********************************************/ //Defines Notification API, not implements it qp.notify = qp.notify || {}; qp.notify.success = function (message, title, options) { qp.log.warn('qp.notify.success is not implemented!'); }; qp.notify.info = function (message, title, options) { qp.log.warn('qp.notify.info is not implemented!'); }; qp.notify.warn = function (message, title, options) { qp.log.warn('qp.notify.warn is not implemented!'); }; qp.notify.error = function (message, title, options) { qp.log.warn('qp.notify.error is not implemented!'); }; /* MESSAGE **************************************************/ //Defines Message API, not implements it qp.message = qp.message || {}; var showMessage = function (message, title, options) { alert((title || '') + ' ' + message); if (!$) { qp.log.warn('qp.message can not return promise since jQuery is not defined!'); return null; } return $.Deferred(function ($dfd) { $dfd.resolve(); }); }; qp.message.info = function (message, title, options) { qp.log.warn('qp.message.info is not implemented!'); return showMessage(message, title, options); }; qp.message.success = function (message, title, options) { qp.log.warn('qp.message.success is not implemented!'); return showMessage(message, title, options); }; qp.message.warn = function (message, title, options) { qp.log.warn('qp.message.warn is not implemented!'); return showMessage(message, title, options); }; qp.message.error = function (message, title, options) { qp.log.warn('qp.message.error is not implemented!'); return showMessage(message, title, options); }; qp.message.confirm = function (message, title, callback, options) { qp.log.warn('qp.message.confirm is not implemented!'); var result = confirm(message); callback && callback(result); if (!$) { qp.log.warn('qp.message can not return promise since jQuery is not defined!'); return null; } return $.Deferred(function ($dfd) { $dfd.resolve(); }); }; /* UI *******************************************************/ qp.ui = qp.ui || {}; /* UI BLOCK */ //Defines UI Block API, not implements it qp.ui.block = function (elm) { qp.log.warn('qp.ui.block is not implemented!'); }; qp.ui.unblock = function (elm) { qp.log.warn('qp.ui.unblock is not implemented!'); }; /* UI BUSY */ //Defines UI Busy API, not implements it qp.ui.setBusy = function (elm, optionsOrPromise) { qp.log.warn('qp.ui.setBusy is not implemented!'); }; qp.ui.clearBusy = function (elm) { qp.log.warn('qp.ui.clearBusy is not implemented!'); }; /* SIMPLE EVENT BUS *****************************************/ qp.event = (function () { var _callbacks = {}; var on = function (eventName, callback) { if (!_callbacks[eventName]) { _callbacks[eventName] = []; } _callbacks[eventName].push(callback); }; var off = function (eventName, callback) { var callbacks = _callbacks[eventName]; if (!callbacks) { return; } var index = -1; for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { index = i; break; } } if (index < 0) { return; } _callbacks[eventName].splice(index, 1); }; var trigger = function (eventName) { var callbacks = _callbacks[eventName]; if (!callbacks || !callbacks.length) { return; } var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < callbacks.length; i++) { callbacks[i].apply(this, args); } }; // Public interface /////////////////////////////////////////////////// return { on: on, off: off, trigger: trigger }; })(); /* UTILS ***************************************************/ qp.utils = qp.utils || {}; /* Creates a name namespace. * Example: * var taskService = qp.utils.createNamespace(qp, 'services.task'); * taskService will be equal to qp.services.task * first argument (root) must be defined first ************************************************************/ qp.utils.createNamespace = function (root, ns) { var parts = ns.split('.'); for (var i = 0; i < parts.length; i++) { if (typeof root[parts[i]] == 'undefined') { root[parts[i]] = {}; } root = root[parts[i]]; } return root; }; /* Find and replaces a string (search) to another string (replacement) in * given string (str). * Example: * qp.utils.replaceAll('This is a test string', 'is', 'X') = 'ThX X a test string' ************************************************************/ qp.utils.replaceAll = function (str, search, replacement) { var fix = search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); return str.replace(new RegExp(fix, 'g'), replacement); }; /* Formats a string just like string.format in C#. * Example: * qp.utils.formatString('Hello {0}','Tuana') = 'Hello Tuana' ************************************************************/ qp.utils.formatString = function () { if (arguments.length < 1) { return null; } var str = arguments[0]; for (var i = 1; i < arguments.length; i++) { var placeHolder = '{' + (i - 1) + '}'; str = qp.utils.replaceAll(str, placeHolder, arguments[i]); } return str; }; qp.utils.toPascalCase = function (str) { if (!str || !str.length) { return str; } if (str.length === 1) { return str.charAt(0).toUpperCase(); } return str.charAt(0).toUpperCase() + str.substr(1); } qp.utils.toCamelCase = function (str) { if (!str || !str.length) { return str; } if (str.length === 1) { return str.charAt(0).toLowerCase(); } return str.charAt(0).toLowerCase() + str.substr(1); } qp.utils.truncateString = function (str, maxLength) { if (!str || !str.length || str.length <= maxLength) { return str; } return str.substr(0, maxLength); }; qp.utils.truncateStringWithPostfix = function (str, maxLength, postfix) { postfix = postfix || '...'; if (!str || !str.length || str.length <= maxLength) { return str; } if (maxLength <= postfix.length) { return postfix.substr(0, maxLength); } return str.substr(0, maxLength - postfix.length) + postfix; }; qp.utils.isFunction = function (obj) { if ($) { //Prefer to use jQuery if possible return $.isFunction(obj); } //alternative for $.isFunction return !!(obj && obj.constructor && obj.call && obj.apply); }; /** * parameterInfos should be an array of { name, value } objects * where name is query string parameter name and value is it's value. * includeQuestionMark is true by default. */ qp.utils.buildQueryString = function (parameterInfos, includeQuestionMark) { if (includeQuestionMark === undefined) { includeQuestionMark = true; } var qs = ''; function addSeperator() { if (!qs.length) { if (includeQuestionMark) { qs = qs + '?'; } } else { qs = qs + '&'; } } for (var i = 0; i < parameterInfos.length; ++i) { var parameterInfo = parameterInfos[i]; if (parameterInfo.value === undefined) { continue; } if (parameterInfo.value === null) { parameterInfo.value = ''; } addSeperator(); if (parameterInfo.value.toJSON && typeof parameterInfo.value.toJSON === "function") { qs = qs + parameterInfo.name + '=' + encodeURIComponent(parameterInfo.value.toJSON()); } else if (Array.isArray(parameterInfo.value) && parameterInfo.value.length) { for (var j = 0; j < parameterInfo.value.length; j++) { if (j > 0) { addSeperator(); } qs = qs + parameterInfo.name + '[' + j + ']=' + encodeURIComponent(parameterInfo.value[j]); } } else { qs = qs + parameterInfo.name + '=' + encodeURIComponent(parameterInfo.value); } } return qs; } /** * Sets a cookie value for given key. * This is a simple implementation created to be used by ABP. * Please use a complete cookie library if you need. * @param {string} key * @param {string} value * @param {Date} expireDate (optional). If not specified the cookie will expire at the end of session. * @param {string} path (optional) */ qp.utils.setCookieValue = function (key, value, expireDate, path, domain) { var cookieValue = encodeURIComponent(key) + '='; if (value) { cookieValue = cookieValue + encodeURIComponent(value); } if (expireDate) { cookieValue = cookieValue + "; expires=" + expireDate.toUTCString(); } if (path) { cookieValue = cookieValue + "; path=" + path; } if (domain) { cookieValue = cookieValue + "; domain=" + domain; } document.cookie = cookieValue; }; /** * Gets a cookie with given key. * This is a simple implementation created to be used by ABP. * Please use a complete cookie library if you need. * @param {string} key * @returns {string} Cookie value or null */ qp.utils.getCookieValue = function (key) { var equalities = document.cookie.split('; '); for (var i = 0; i < equalities.length; i++) { if (!equalities[i]) { continue; } var splitted = equalities[i].split('='); if (splitted.length != 2) { continue; } if (decodeURIComponent(splitted[0]) === key) { return decodeURIComponent(splitted[1] || ''); } } return null; }; /** * Deletes cookie for given key. * This is a simple implementation created to be used by ABP. * Please use a complete cookie library if you need. * @param {string} key * @param {string} path (optional) */ qp.utils.deleteCookie = function (key, path) { var cookieValue = encodeURIComponent(key) + '='; cookieValue = cookieValue + "; expires=" + (new Date(new Date().getTime() - 86400000)).toUTCString(); if (path) { cookieValue = cookieValue + "; path=" + path; } document.cookie = cookieValue; } /** * Gets the domain of given url * @param {string} url * @returns {string} */ qp.utils.getDomain = function (url) { var domainRegex = /(https?:){0,1}\/\/((?:[\w\d-]+\.)+[\w\d]{2,})/i; var matches = domainRegex.exec(url); return (matches && matches[2]) ? matches[2] : ''; } /* TIMING *****************************************/ qp.timing = qp.timing || {}; qp.timing.utcClockProvider = (function () { var toUtc = function (date) { return Date.UTC( date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds() ); } var now = function () { return toUtc(new Date()); }; var normalize = function (date) { if (!date) { return date; } return new Date(toUtc(date)); }; // Public interface /////////////////////////////////////////////////// return { now: now, normalize: normalize, supportsMultipleTimezone: true }; })(); qp.timing.localClockProvider = (function () { var toLocal = function (date) { return new Date( date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds() ); } var now = function () { return toLocal(new Date()); } var normalize = function (date) { if (!date) { return date; } return toLocal(date); } // Public interface /////////////////////////////////////////////////// return { now: now, normalize: normalize, supportsMultipleTimezone: false }; })(); qp.timing.unspecifiedClockProvider = (function () { var now = function () { return new Date(); } var normalize = function (date) { return date; } // Public interface /////////////////////////////////////////////////// return { now: now, normalize: normalize, supportsMultipleTimezone: false }; })(); qp.timing.convertToUserTimezone = function (date) { var localTime = date.getTime(); var utcTime = localTime + (date.getTimezoneOffset() * 60000); var targetTime = parseInt(utcTime) + parseInt(qp.timing.timeZoneInfo.windows.currentUtcOffsetInMilliseconds); return new Date(targetTime); }; /* CLOCK *****************************************/ qp.clock = qp.clock || {}; qp.clock.now = function () { if (qp.clock.provider) { return qp.clock.provider.now(); } return new Date(); } qp.clock.normalize = function (date) { if (qp.clock.provider) { return qp.clock.provider.normalize(date); } return date; } qp.clock.provider = qp.timing.unspecifiedClockProvider; /* SECURITY ***************************************/ qp.security = qp.security || {}; qp.security.antiForgery = qp.security.antiForgery || {}; qp.security.antiForgery.tokenCookieName = 'XSRF-TOKEN'; qp.security.antiForgery.tokenHeaderName = 'X-XSRF-TOKEN'; qp.security.antiForgery.getToken = function () { return qp.utils.getCookieValue(qp.security.antiForgery.tokenCookieName); }; qp.security.antiForgery.shouldSendToken = function (settings) { if (settings.crossDomain === undefined || settings.crossDomain === null) { return qp.utils.getDomain(location.href) === qp.utils.getDomain(settings.url); } return !settings.crossDomain; }; return qp; })(); }); }(typeof define === 'function' && define.amd ? define : function (deps, factory) { if (typeof module !== 'undefined' && module.exports) { module.exports = factory(require('jquery')); } else { window.qp = factory(window.jQuery); } }));