@moderntribe/wme-utils
Version:
Common utilities used in the WME ecosystem
116 lines (108 loc) • 2.94 kB
JavaScript
const beforeUnloadListener = (event) => {
event.preventDefault();
// eslint-disable-next-line no-param-reassign
event.returnValue = 'Changes you made may not be saved.';
return event;
};
/**
* Submit payload for use by WME Ajax Action
*
* @param {HandleActionPayloadInterface} payload - Data for use as payload
* @example
* {
* _wpnonce: '',
* action: '',
* sub_action: ''
* }
* @return {Promise}
*/
const handleActionRequest = (payload) => {
const promise = new Promise((resolve, reject) => {
window.wp.ajax.post(payload).done((response) => {
resolve(response || 'success');
}).catch((response) => {
if (response) {
reject(response?.responseJSON ? response.responseJSON.data : response.responseText);
}
reject();
});
});
return promise;
};
/**
* Check if sting is a valud URL
*
* @param {string} url - String to check
* @return {boolean} - Is url valid
*/
const isValidUrl = (url) => {
try {
const urlTest = new URL(url);
return true;
}
catch (error) {
return false;
}
};
/**
* Convert object into FormData object
*
* @param {Object} data - Object to convert
* @return {FormData} - FormData object
*/
const objToFormData = (data) => {
const formData = new FormData();
Object.keys(data).forEach((key) => {
formData.append(key, data[key]);
});
return formData;
};
/**
* Converts a pixel unit into Rem
*
* @param {number} size - Pixel value
* @param {number} rootFontSize - Root font size for document
* @return {string | null} Rem unit
*/
const pxToRem = (size, rootFontSize = 16) => {
if (typeof size === 'number' && typeof rootFontSize === 'number') {
return `${parseFloat((size / rootFontSize).toFixed(4))}rem`;
}
return null;
};
/**
* Create randome number between min and max.
*
* @param {number} min
* @param {number} max
* @return {number} - Random number
*/
const randomInt = (min, max) => {
const minValue = Math.ceil(min);
const maxValue = Math.floor(max);
// eslint-disable-next-line no-mixed-operators
return Math.floor(Math.random() * (maxValue - minValue) + minValue);
};
/**
* Removes empty items from object.
*
* @see https://stackoverflow.com/a/70363240
*
* @param {Object} object
* @return {Object} - Returns object with emtpy items removed.
*/
function removeNulls(object) {
const newObject = object;
if (typeof newObject === 'object'
&& newObject !== null
&& !Array.isArray(newObject)) {
Object.keys(newObject).forEach((key) => {
if (newObject[key] === null) {
delete newObject[key];
}
});
}
return newObject;
}
export { beforeUnloadListener, handleActionRequest, isValidUrl, objToFormData, pxToRem, randomInt, removeNulls };
//# sourceMappingURL=index.js.map