@zohodesk/components
Version:
In this Package, we Provide Some Basic Components to Build Web App
416 lines (365 loc) • 12.1 kB
JavaScript
//$Id$//
import viewPort from "../Popup/viewPort";
const {
frameRelativeRects
} = viewPort;
export const cs = classArr => classArr.filter(name => name).join(' ');
export const parseDecimal = val => val ? parseFloat(val) : 0;
export const getTotalDimension = (elem, align) => {
const style = window.getComputedStyle(elem);
return align === 'vertical' ? elem.offsetWidth + parseDecimal(style.marginLeft) + parseDecimal(style.marginRight) : elem.offsetHeight + parseDecimal(style.marginTop) + parseDecimal(style.marginBottom);
};
export function stopPropagation(e) {
e && e.stopPropagation && e.stopPropagation();
}
;
export const stopAllEventPropagation = e => {
e.stopPropagation && e.stopPropagation();
e.nativeEvent && e.nativeEvent.stopImmediatePropagation && e.nativeEvent.stopImmediatePropagation();
};
export function cancelBubblingEffect(e) {
e && e.stopPropagation && e.stopPropagation();
e && e.nativeEvent && e.nativeEvent.stopImmediatePropagation && e.nativeEvent.stopImmediatePropagation();
}
export function getKeyValue(event) {
return event && event.key && event.key;
} // export function getCommentsDetails(
// commentIds = [],
// comments = {},
// agents = {}
// ) {
// return (
// commentIds.map(commentId => {
// const comment = comments[commentId] || {};
// const commentedBy = comment.commenterId || null;
// return Object.assign({}, comment, { commentedBy: agents[commentedBy] });
// }) || []
// );
// }
export function encodeForHtml(str) {
if (/<|>|&|"|'|\\/g.test(str) == true) {
str = str.replace(/&/g, '&');
str = str.replace(/</g, '<');
str = str.replace(/>/g, '>');
str = str.replace(/"/g, '"');
str = str.replace(/\\/g, '\');
str = str.replace(/'/g, ''');
}
return str;
}
export function getListOfDetails() {
let Obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let fn = arguments.length > 1 ? arguments[1] : undefined;
const ids = Object.keys(Obj) || [];
return ids.map(id => fn(Obj[id]));
}
export function capitalize() {
let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
let newValue = '';
for (let i = 0; i < value.length; i++) {
if (i == 0) {
newValue += value[i].toUpperCase();
} else {
newValue += value[i].toLowerCase();
}
}
return newValue;
}
export function bind() {
for (var _len = arguments.length, handlers = new Array(_len), _key = 0; _key < _len; _key++) {
handlers[_key] = arguments[_key];
}
handlers.forEach(handler => {
this[handler] = this[handler].bind(this);
});
}
export function getFullName() {
let firstName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
let lastName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
let fullName = '';
if (firstName !== null && firstName !== '') {
fullName = firstName;
}
if (lastName !== null && lastName !== '') {
fullName = `${fullName}${lastName}`;
}
return fullName;
}
export function getStringifiedOutputForJson() {
let input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const keys = Object.keys(input);
const modifiedInput = keys.reduce((curr, next) => {
const values = input[next] || [];
if (values.length) {
const valueList = values.reduce((curr, next) => {
curr.push(next.id);
return curr;
}, []);
curr[next] = valueList;
return curr;
}
return curr;
}, {});
return JSON.stringify(modifiedInput);
}
export function mapValues(obj, fn) {
return obj && Object.keys(obj).reduce((res, key) => {
res[key] = fn(key, obj[key]);
return res;
}, {}) || obj;
}
export function filterValue(obj, val) {
let result;
const ids = obj ? Object.keys(obj) : [];
ids.forEach(key => {
const value = obj[key] || {};
if (value.name === val && !value.isCustomField) {
result = value.id;
}
});
return result;
}
export function merge() {
let oldObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let newObj = arguments.length > 1 ? arguments[1] : undefined;
const copyOfOld = Object.assign({}, oldObj);
return Object.keys(newObj).reduce((res, key) => {
res[key] = Object.assign({}, res[key] || {}, newObj[key]);
return res;
}, copyOfOld);
}
export function formatValue() {
let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let valueField = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'id';
let textField = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'name';
return values && values.map(value => {
let formattedValue = value;
if (typeof value === 'string' || typeof value === 'number') {
formattedValue = {};
formattedValue[valueField] = value;
formattedValue[textField] = value;
}
return formattedValue;
}) || [];
}
export function bytesToSize(bytes) {
bytes = parseInt(bytes, 10);
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) {
return '0 Byte';
}
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10);
return `${Math.round(bytes / Math.pow(1024, i), 2)} ${sizes[i]}`;
}
export function getMemSize(bytes) {
let size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : !0;
const thresh = size ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return `${bytes} B`;
}
let units = size ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
i = -1;
do {
bytes /= thresh, ++i;
} while (Math.abs(bytes) >= thresh && i < units.length - 1);
{
return `${bytes.toFixed(1)} ${units[i]}`;
}
}
export function checkIsImageFile(fileName) {
fileName = fileName || '';
return /jpeg|jpg|png|gif|bmp|tiff|tif|ico/gi.test(fileName.substr(fileName.lastIndexOf('.') + 1));
}
function getI18NValue(key, values) {
if (typeof i18n === 'undefined' || key === '' || typeof key === 'undefined') {
return key;
}
let i18nStr = i18n[key];
if (i18nStr === undefined) {
return key;
}
i18nStr = replaceI18NValuesWithRegex(i18nStr, values);
return unescapeUnicode(i18nStr);
}
global.getI18NValue = getI18NValue;
function replaceI18NValuesWithRegex(i18nStr, values) {
if (typeof values !== 'undefined') {
if (Array.isArray(values)) {
for (let i = 0; i < values.length; i++) {
i18nStr = i18nStr.replace(new RegExp(`\\{${i}\\}`, 'g'), values[i]);
}
} else {
i18nStr = i18nStr.replace(new RegExp('\\{0\\}', 'g'), values);
}
}
return i18nStr;
}
function unescapeUnicode(str) {
return str.replace(/\\u([a-fA-F0-9]{4})/g, (g, m1) => String.fromCharCode(parseInt(m1, 16)));
}
export function getPortalName(portalList, portalId) {
return portalList && portalList.reduce((res, portal) => {
if (portal.orgId === portalId) {
return portal.orgName;
}
return res;
}, null);
}
export function getFullDateString(fullDateObj) {
let dateStr = '';
const monthArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (fullDateObj.toDateString() == new Date().toDateString()) {
dateStr = format12Hour(fullDateObj);
} else {
const year = fullDateObj.getFullYear();
const month = monthArr[fullDateObj.getMonth()];
const date = fullDateObj.getDate();
const time = format12Hour(fullDateObj);
dateStr = `${month} ${date} ${year} ${time}`;
}
return dateStr;
}
export function format12Hour(date) {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'pm' : 'am';
hours %= 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? `0${minutes}` : minutes;
const strTime = `${hours}:${minutes} ${ampm}`;
return strTime;
}
export function getDateOnly(fullDateObj) {
let dateStr = '';
const monthArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (fullDateObj.toDateString() == new Date().toDateString()) {
dateStr = 'Today';
} else {
const year = fullDateObj.getFullYear();
const month = monthArr[fullDateObj.getMonth()];
const date = fullDateObj.getDate();
dateStr = `${month} ${date} ${year}`;
}
return dateStr;
}
export function doAfterScrollEnd(element, callback) {
const {
scrollTop
} = element;
const {
clientHeight
} = element;
const {
scrollHeight
} = element;
const scrollPercent = scrollTop / (scrollHeight - clientHeight) * 100;
if (scrollPercent > 80) {
callback && callback();
}
}
export const debounce = function (func, wait) {
let interval;
return function (e) {
clearTimeout(interval);
interval = setTimeout(func.bind(undefined, e), wait);
};
};
let timerId;
export const throttle = function (func, wait) {
for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
if (timerId) {
return;
}
timerId = setTimeout(() => {
try {
func(...args);
} finally {
timerId = undefined;
}
}, wait);
};
export const scrollTo = function (suggestionContainer, selSuggestion) {
if (!suggestionContainer || !selSuggestion) {
return;
}
const {
rectGap
} = frameRelativeRects(selSuggestion, suggestionContainer) || {};
const {
top = 0,
bottom = 0
} = rectGap || {};
if (top < 0 && bottom < 0) {
return;
}
const isElementInViewPort = top < 0 || bottom < 0 ? false : true;
const suggestionContainerScrollTop = suggestionContainer.scrollTop;
suggestionContainer.scrollTop = !isElementInViewPort ? bottom < 0 ? suggestionContainer.scrollTop + Math.abs(bottom) : top < 0 ? suggestionContainer.scrollTop - Math.abs(top) : suggestionContainerScrollTop : suggestionContainerScrollTop;
};
export const getIsEmptyValue = value => typeof value === 'string' ? value.trim() ? false : true : value === 0 || value ? false : true;
export function remConvert(val) {
const baseValue = parseFloat(window.getComputedStyle(document.body).getPropertyValue('font-size')).toFixed(4);
return (val / baseValue).toPrecision(4);
}
export function isDescendant(parent, child) {
let node = child.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
export function getElementSpace(elementRef) {
let neededSpace = 0,
availableInsideSpace = 0;
if (elementRef) {
let getStyle = window.getComputedStyle(elementRef);
let margin = parseFloat(getStyle.marginLeft) + parseFloat(getStyle.marginRight);
let padding = parseFloat(getStyle.paddingLeft) + parseFloat(getStyle.paddingRight);
let width = parseFloat(elementRef.offsetWidth);
neededSpace = width + margin;
availableInsideSpace = width - padding;
}
return {
neededSpace: neededSpace,
availableInsideSpace: availableInsideSpace
};
}
export function getSearchString() {
let charachers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return (charachers || '').toString().toLowerCase(); //.replace(/\s+/g, '');
}
export function findScrollEnd(element) {
let {
scrollHeight,
scrollTop,
offsetHeight,
clientHeight
} = element || {};
let isElementScrollable = scrollHeight > clientHeight;
if (isElementScrollable) {
if (scrollHeight <= Math.ceil(scrollTop + offsetHeight)) {
return true;
}
} // else {
// throw 'Is scroll not present in this element';
// }
return false;
}
export function isTextSelected() {
let selectedText = '';
if (window.getSelection) {
selectedText = window.getSelection().toString();
} else if (document.getSelection) {
selectedText = document.getSelection().toString();
}
if (selectedText !== '') {
return true;
}
return false;
}
export const DUMMY_OBJECT = {};