react-js-plugins
Version:
A powerful and efficient React utility library designed to enhance application performance by streamlining and simplifying the management of complex asynchronous operations.
797 lines (796 loc) • 31.4 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import moment from "moment";
import * as Yup from 'yup';
import { _deepClone, isWindowReady } from "./chunk65431";
export var _scrollToTop = function () {
if (!isWindowReady()) {
return;
}
window.scrollTo({ top: 0, behavior: "smooth" });
};
export var _batchProcess = function (data, batchSize, processFn) { return __awaiter(void 0, void 0, void 0, function () {
var i, batch;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
i = 0;
_a.label = 1;
case 1:
if (!(i < data.length)) return [3 /*break*/, 4];
batch = data.slice(i, i + batchSize);
return [4 /*yield*/, Promise.all(batch.map(processFn))];
case 2:
_a.sent();
_a.label = 3;
case 3:
i += batchSize;
return [3 /*break*/, 1];
case 4: return [2 /*return*/];
}
});
}); };
export var _flattenObject = function (obj, prefix) {
if (prefix === void 0) { prefix = ''; }
var result = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var newKey = prefix ? "".concat(prefix, ".").concat(key) : key;
if (typeof obj[key] === 'object' && obj[key] !== null) {
result = __assign(__assign({}, result), _flattenObject(obj[key], newKey));
}
else {
result[newKey] = obj[key];
}
}
}
return result;
};
export var _deepMerge = function (target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
if (typeof source[key] === 'object' && source[key] !== null && target[key]) {
target[key] = _deepMerge(target[key], source[key]);
}
else {
target[key] = source[key];
}
}
}
return target;
};
export var _chunk = function (arr, size) {
var result = [];
for (var i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
};
export var _asyncDebounce = function (fn, delay) {
var timeout;
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
clearTimeout(timeout);
timeout = setTimeout(function () { return fn.apply(void 0, args); }, delay);
return [2 /*return*/];
});
});
};
};
export function _throttle(func, limit) {
var inThrottle;
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!inThrottle) {
func.apply(void 0, args);
inThrottle = true;
setTimeout(function () { return (inThrottle = false); }, limit);
}
};
}
export var _deepCloneArray = function (arr) {
return arr.map(function (item) { return (typeof item === 'object' ? _deepClone(item) : item); });
};
export var _getMaxMinValue = function (arr) {
return arr.reduce(function (acc, curr) {
if (curr > acc.max)
acc.max = curr;
if (curr < acc.min)
acc.min = curr;
return acc;
}, { max: -Infinity, min: Infinity });
};
export var _asyncMap = function (arr, asyncFn) { return __awaiter(void 0, void 0, void 0, function () {
var results, i, _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
results = [];
i = 0;
_c.label = 1;
case 1:
if (!(i < arr.length)) return [3 /*break*/, 4];
_b = (_a = results).push;
return [4 /*yield*/, asyncFn(arr[i])];
case 2:
_b.apply(_a, [_c.sent()]);
_c.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, results];
}
});
}); };
export var _transformAsyncData = function (arr, transformer) { return __awaiter(void 0, void 0, void 0, function () {
var result, i, transformedItem;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
result = [];
i = 0;
_a.label = 1;
case 1:
if (!(i < arr.length)) return [3 /*break*/, 4];
return [4 /*yield*/, transformer(arr[i])];
case 2:
transformedItem = _a.sent();
result.push(transformedItem);
_a.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, result];
}
});
}); };
export var _getNestedProperty = function (obj, path) {
return path.split('.').reduce(function (acc, key) { return acc && acc[key]; }, obj);
};
export var _deepEqual = function (obj1, obj2) {
if (obj1 === obj2)
return true;
if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null)
return false;
var keys1 = Object.keys(obj1);
var keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length)
return false;
for (var _i = 0, keys1_1 = keys1; _i < keys1_1.length; _i++) {
var key = keys1_1[_i];
if (!keys2.includes(key))
return false;
if (!_deepEqual(obj1[key], obj2[key]))
return false;
}
return true;
};
export var _mergeArrays = function (arr1, arr2) {
return Array.from(new Set(__spreadArray(__spreadArray([], arr1, true), arr2, true)));
};
export var _filterDuplicates = function (arr, uniqueKey) {
var seen = new Set();
return arr.filter(function (item) {
var key = item[uniqueKey];
if (seen.has(key))
return false;
seen.add(key);
return true;
});
};
export var _sortByKey = function (arr, key) {
return arr.sort(function (a, b) { return (a[key] > b[key] ? 1 : -1); });
};
export var _mapAsync = function (arr, asyncFn) { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Promise.all(arr.map(asyncFn))];
case 1:
result = _a.sent();
return [2 /*return*/, result];
}
});
}); };
export var _formatDate = function (date, format) {
var options = {};
if (format.includes('Y'))
options.year = 'numeric';
if (format.includes('M'))
options.month = 'short';
if (format.includes('D'))
options.day = 'numeric';
return new Intl.DateTimeFormat('en-US', options).format(date);
};
export function _localeDateFormat(date, locale, options) {
if (locale === void 0) { locale = 'en-IN'; }
return new Intl.DateTimeFormat(locale, __assign({ year: 'numeric', month: 'short', day: 'numeric' }, options)).format(new Date(date));
}
export var _calPercentage = function (value, total) {
if (total === 0)
return 0;
return (value / total) * 100;
};
export var _sum = function (numbers) {
return numbers.reduce(function (acc, num) { return acc + num; }, 0);
};
export var _average = function (numbers) {
var total = _sum(numbers);
return total / numbers.length;
};
export var _getPriceAfterTax = function (price, taxRate) {
return price * (1 + taxRate / 100);
};
export var _calculateTimeDifference = function (startDate, endDate) {
var diffInMilliseconds = endDate.getTime() - startDate.getTime();
var days = Math.floor(diffInMilliseconds / (1000 * 3600 * 24));
var hours = Math.floor((diffInMilliseconds % (1000 * 3600 * 24)) / (1000 * 3600));
var minutes = Math.floor((diffInMilliseconds % (1000 * 3600)) / (1000 * 60));
var seconds = Math.floor((diffInMilliseconds % (1000 * 60)) / 1000);
return "".concat(days, "d ").concat(hours, "h ").concat(minutes, "m ").concat(seconds, "s");
};
export var _arrayIncludesObject = function (arr, obj) {
return arr.some(function (item) { return JSON.stringify(item) === JSON.stringify(obj); });
};
export var _toCamelCase = function (str) {
return str.replace(/([-_][a-z])/g, function (group) { return group.toUpperCase().replace('-', '').replace('_', ''); });
};
export var _freeze = function (obj) {
if (typeof obj !== "object" || obj === null) {
console.error("Error: Provided value is not a valid object.");
return null;
}
if (Object.isFrozen(obj)) {
console.error("Error: This object is already frozen.");
return obj;
}
return Object.freeze(obj);
};
export var _isFreeze = function (obj) {
if (typeof obj !== "object" || obj === null) {
console.error("Error: Provided value is not a valid object.");
return false;
}
return Object.isFrozen(obj);
};
export var _seal = function (obj) {
if (typeof obj !== "object" || obj === null) {
console.error("Error: Provided value is not a valid plain object.");
return null;
}
if (Object.isFrozen(obj)) {
console.error("Error: Cannot seal a frozen object.");
return obj;
}
return Object.seal(obj);
};
export var _isSeal = function (obj) {
if (typeof obj !== "object" || obj === null) {
console.error("Error: Provided value is not a valid object.");
return false;
}
return Object.isSealed(obj);
};
export var _arrayToObject = function (arr) {
var obj = {};
for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) {
var _a = arr_1[_i], key = _a[0], value = _a[1];
obj[key] = value;
}
return obj;
};
export var _objectToArray = function (obj) {
var result = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
result.push([key, obj[key]]);
}
}
return result;
};
export var _arrayToObjectByKey = function (arr, key) {
return arr.reduce(function (acc, curr) {
acc[curr[key]] = curr;
return acc;
}, {});
};
export var _isInArray = function (arr, value) { return arr.includes(value); };
export var _getObjectValues = function (obj) { return Object.values(obj); };
export var _swapArrayElements = function (arr, index1, index2) {
var temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
};
export var _filterObjectByKey = function (obj, keys) {
return Object.fromEntries(Object.entries(obj).filter(function (_a) {
var key = _a[0];
return keys.includes(key);
}));
};
export var _getScrollPosition = function () {
if (!isWindowReady()) {
return { scrollX: 0, scrollY: 0 };
}
return {
scrollX: window.scrollX,
scrollY: window.scrollY,
};
};
export var _arrayIntersection = function (arr1, arr2) {
if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
console.error("Both parameters must be arrays.");
return [];
}
return arr1.filter(function (item) { return arr2.includes(item); });
};
export var _getArrayOfObjectsByProperty = function (arr, key, value) {
return arr.filter(function (item) { return item[key] === value; });
};
export var _downloadBlob = function (blob, filename) {
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
export var _downloadFile = function (response, defaultName) {
if (defaultName === void 0) { defaultName = 'downloadedFile'; }
try {
var contentType = response.headers['content-type'];
var fileName = defaultName;
if (contentType === 'application/pdf')
fileName += '.pdf';
else if (contentType === 'image/png')
fileName += '.png';
else if (contentType === 'image/jpeg')
fileName += '.jpg';
else if (contentType === 'text/csv')
fileName += '.csv';
else if (contentType === 'application/vnd.ms-excel')
fileName += '.xls';
else if (contentType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
fileName += '.xlsx';
else if (contentType === 'application/zip')
fileName += '.zip';
var blob = new Blob([response.data], { type: contentType });
var url_1 = window.URL.createObjectURL(blob);
var link_1 = document.createElement('a');
link_1.href = url_1;
link_1.download = fileName;
document.body.appendChild(link_1);
link_1.click();
setTimeout(function () {
window.URL.revokeObjectURL(url_1);
document.body.removeChild(link_1);
}, 100);
}
catch (err) {
console.error('Error downloading file:', err);
throw err;
}
};
export var _fileToBase64 = function (file) {
return new Promise(function (resolve, reject) {
if (!file || !(file instanceof File)) {
reject(new Error('No valid file provided'));
return;
}
var reader = new FileReader();
reader.onload = function () {
if (typeof reader.result === 'string') {
var base64String = reader.result.split(",")[1];
if (base64String) {
resolve(base64String);
}
else {
reject(new Error("Failed to extract base64 data"));
}
}
else {
reject(new Error("Invalid file format"));
}
};
reader.onerror = function () { return reject(new Error("Failed to read file")); };
reader.readAsDataURL(file);
});
};
export var _base64ToBlob = function (base64) {
var binaryString = atob(base64.split(',')[1]);
var array = [];
for (var i = 0; i < binaryString.length; i++) {
array.push(binaryString.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], { type: 'application/octet-stream' });
};
export var _downloadBase64File = function (base64Data, fileName) {
var _a, _b;
try {
if (!base64Data || typeof base64Data !== 'string') {
throw new Error('Invalid base64 data provided.');
}
if (!fileName || typeof fileName !== 'string') {
throw new Error('A valid file name is required.');
}
var hasPrefix = base64Data.startsWith('data:');
if (!hasPrefix) {
var extension = (_b = (_a = fileName.split('.').pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : '';
var mimeTypes = {
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
png: 'image/png',
svg: 'image/svg+xml',
pdf: 'application/pdf',
csv: 'text/csv',
xls: 'application/vnd.ms-excel',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
};
var mimeType = mimeTypes[extension] || 'application/octet-stream';
base64Data = "data:".concat(mimeType, ";base64,").concat(base64Data);
}
if (!base64Data.includes('base64,')) {
throw new Error('Base64 string is missing proper format.');
}
var link = document.createElement('a');
link.href = base64Data;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
catch (error) {
console.error('Download failed:', error.message);
}
};
export var _initializeFormValues = function (fields) {
return fields.reduce(function (acc, field) {
acc[field] = ''; // default value
return acc;
}, {});
};
export var _dynamicRequiredValidation = function (requiredFields) {
var schema = {};
requiredFields.forEach(function (field) {
schema[field] = Yup.string().required("".concat(field, " is required"));
});
return Yup.object(schema);
};
export var _generateYupValidation = function (fields) {
var schema = {};
fields.forEach(function (field) {
schema[field] = Yup.string().required("".concat(field, " is required"));
});
return Yup.object(schema);
};
export var _initializeFormikFields = function (fields) {
return fields.reduce(function (acc, field) {
acc[field] = ''; // set default value for each field
return acc;
}, {});
};
export var _setNestedProperty = function (obj, path, value) {
var keys = path.split('.');
keys.reduce(function (acc, key, idx) {
if (idx === keys.length - 1) {
acc[key] = value;
}
else {
acc[key] = acc[key] || {};
}
return acc[key];
}, obj);
};
export var _transformArray = function (arr, transformFn) {
return arr.map(transformFn);
};
export var _findObjectById = function (arr, id) {
return arr.find(function (item) { return item.id === id; });
};
export var _getUniqueValues = function (arr) {
return Array.from(new Set(arr));
};
export var _mergeArraysByKey = function (arr1, arr2, key) {
var map = new Map();
arr1.forEach(function (item) { return map.set(item[key], item); });
arr2.forEach(function (item) {
if (map.has(item[key])) {
map.set(item[key], __assign(__assign({}, map.get(item[key])), item));
}
else {
map.set(item[key], item);
}
});
return Array.from(map.values());
};
export var _removeDuplicates = function (arr, key) {
var seen = new Set();
return arr.filter(function (item) {
var value = item[key];
if (!seen.has(value)) {
seen.add(value);
return true;
}
return false;
});
};
export var _groupBy = function (arr, key) {
return arr.reduce(function (result, currentValue) {
(result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
return result;
}, {});
};
export var _arrayDiff = function (arr1, arr2) {
return arr1.filter(function (item) { return !arr2.includes(item); });
};
export var _deepCompareArrays = function (arr1, arr2) {
if (arr1.length !== arr2.length)
return false;
return arr1.every(function (item, index) { return _deepEqual(item, arr2[index]); });
};
export var _updateObjectInArray = function (arr, key, value, update) {
return arr.map(function (item) {
return item[key] === value ? __assign(__assign({}, item), update) : item;
});
};
export var _getKeyByValue = function (obj, value) {
var _a;
if (!obj || typeof obj !== 'object')
return null;
return (_a = Object.keys(obj).find(function (key) { return obj[key] === value; })) !== null && _a !== void 0 ? _a : null;
};
export var _getValueByKey = function (obj, key) {
var _a;
if (!obj || typeof obj !== 'object')
return '';
return (_a = obj[key]) !== null && _a !== void 0 ? _a : '';
};
export var _getKeysByValue = function (obj, value) {
if (!obj || typeof obj !== 'object')
return [];
return Object.keys(obj).filter(function (key) { return obj[key] === value; });
};
export var _dateFormat = function (date, format) {
if (format === void 0) { format = 'DD/MM/YYYY HH:mm:ss'; }
return moment(date).format(format);
};
export var _dateTransformer = function (data) {
if (data instanceof Date) {
return _dateFormat(data, 'YYYY-MM-DDTHH:mm:ssZ');
}
if (Array.isArray(data)) {
return data.map(_dateTransformer);
}
if (typeof data === 'object' && data !== null) {
return Object.fromEntries(Object.entries(data).map(function (_a) {
var key = _a[0], value = _a[1];
return [key, _dateTransformer(value)];
}));
}
return data;
};
export var _escapeRegExpMatch = function (s) {
return s.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&');
};
export var _isExactMatch = function (str, match) {
return new RegExp("\\b".concat(_escapeRegExpMatch(match), "\\b")).test(str);
};
export var _bytesToSize = function (bytes, decimals) {
if (decimals === void 0) { decimals = 2; }
if (bytes === 0) {
return '0 Bytes';
}
var k = 1024;
var dm = decimals < 0 ? 0 : decimals;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return "".concat(parseFloat((bytes / Math.pow(k, i)).toFixed(dm)), " ").concat(sizes[i]);
};
export var _swapArrayByKey = function (arr, key) {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length - 1; j++) {
if (arr[j][key] < arr[j + 1][key]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
};
export var _setTouchedFields = function (formRef, errors) {
if ((formRef === null || formRef === void 0 ? void 0 : formRef.current) && errors) {
formRef.current.setTouched(Object.fromEntries(Object.keys(errors).map(function (key) { return [key, true]; })), true);
}
};
export var _isValidForm = function (formRef) { return __awaiter(void 0, void 0, void 0, function () {
var errors, isValid;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(formRef === null || formRef === void 0 ? void 0 : formRef.current))
return [2 /*return*/, false];
return [4 /*yield*/, formRef.current.validateForm()];
case 1:
errors = _a.sent();
isValid = Object.keys(errors).length === 0;
if (!isValid) {
formRef.current.setTouched(Object.fromEntries(Object.keys(errors).map(function (key) { return [key, true]; })), true);
}
return [2 /*return*/, isValid];
}
});
}); };
export var _isStepValid = function (formRef, fieldsToCheck) { return __awaiter(void 0, void 0, void 0, function () {
var touchedFields, errors, stepErrors;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(formRef === null || formRef === void 0 ? void 0 : formRef.current))
return [2 /*return*/, false];
touchedFields = fieldsToCheck.reduce(function (acc, field) {
acc[field] = true;
return acc;
}, {});
return [4 /*yield*/, formRef.current.setTouched(touchedFields, true)];
case 1:
_a.sent();
return [4 /*yield*/, formRef.current.validateForm()];
case 2:
errors = _a.sent();
stepErrors = Object.keys(errors).filter(function (key) { return fieldsToCheck.includes(key); });
return [2 /*return*/, stepErrors.length === 0];
}
});
}); };
export var _validateFormRef = function (formRef) { return __awaiter(void 0, void 0, void 0, function () {
var errors, isValid;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(formRef && formRef.current)) return [3 /*break*/, 2];
return [4 /*yield*/, formRef.current.validateForm()];
case 1:
errors = _a.sent();
isValid = Object.keys(errors).length === 0;
return [2 /*return*/, { isValid: isValid, errors: isValid ? [] : errors }];
case 2: return [2 /*return*/, { isValid: false, errors: [] }];
}
});
}); };
export var _handleParentsMenu = function (currentArr, menuID) {
if (!menuID)
return;
var parent = currentArr.find(function (item) { return item.data.menuID === menuID; });
if (!parent)
return;
var anyChildChecked = currentArr.some(function (child) { return child.data.parentMenuID === parent.data.menuID && child.data.isAssigned; });
if (parent.data.isAssigned !== anyChildChecked) {
parent.data.isAssigned = anyChildChecked;
parent.data.permissions = Object.fromEntries(Object.keys(parent.data.permissions).map(function (key) { return [key, anyChildChecked]; }));
_handleParentsMenu(currentArr, parent.data.parentMenuID);
}
};
export var _handleParentNode = function (currentArr, menuID, permissionKey) {
var _a;
if (!menuID)
return;
var parent = currentArr.find(function (item) { return item.data.menuID === menuID; });
if (!parent)
return;
var childPermissions = currentArr
.filter(function (child) { return child.data.parentMenuID === parent.data.menuID; })
.flatMap(function (child) { return Object.values(child.data.permissions); });
var anyChildHasPermission = childPermissions.some(Boolean);
var anyChildHasSpecificPermission = currentArr.some(function (child) { return child.data.parentMenuID === parent.data.menuID && Boolean(child.data.permissions[permissionKey]); });
var updatedPermissions = __assign(__assign({}, parent.data.permissions), (_a = {}, _a[permissionKey] = anyChildHasSpecificPermission, _a));
var readPermissionKey = Object.keys(updatedPermissions).find(function (key) { return key.toLowerCase().includes('read'); });
if (readPermissionKey) {
updatedPermissions[readPermissionKey] = anyChildHasPermission;
}
parent.data.permissions = updatedPermissions;
parent.data.isAssigned = anyChildHasPermission;
_handleParentNode(currentArr, parent.data.parentMenuID, permissionKey);
};
export var _handleChildrenMenu = function (currentArr, parentKey, checked) {
currentArr.forEach(function (ele) {
if (ele.data.parentMenuID === parentKey && ele.data.isAssigned !== checked) {
ele.data.isAssigned = checked;
ele.data.permissions = Object.fromEntries(Object.keys(ele.data.permissions).map(function (key) { return [key, checked]; }));
_handleChildrenMenu(currentArr, ele.data.menuID, checked);
}
});
};
export var _handlePermissions = function (currentArr, currentObj, permissionKey, isChecked) {
return currentArr.map(function (obj) {
var _a;
if (obj.data.menuID === currentObj.data.menuID) {
var updatedPermissions = __assign(__assign({}, obj.data.permissions), (_a = {}, _a[permissionKey] = isChecked, _a));
var readPermissionKey_1 = Object.keys(updatedPermissions).find(function (key) { return key.toLowerCase().includes('read'); });
if (readPermissionKey_1) {
if (isChecked) {
updatedPermissions[readPermissionKey_1] = true;
}
else {
var otherPermissionsChecked = Object.entries(updatedPermissions)
.filter(function (_a) {
var key = _a[0];
return key !== readPermissionKey_1;
})
.some(function (_a) {
var value = _a[1];
return value;
});
updatedPermissions[readPermissionKey_1] = otherPermissionsChecked;
}
}
return __assign(__assign({}, obj), { data: __assign(__assign({}, obj.data), { permissions: updatedPermissions, isAssigned: Object.values(updatedPermissions).some(Boolean) }) });
}
return obj;
});
};
export var _isValidYupSchema = function (schema) {
return Yup.isSchema(schema);
};