@trap_stevo/legendarybuilderproreact-ui
Version:
The legendary UI & utility API that makes your application a legendary application. ~ Created by Steven Compton
1,343 lines (1,339 loc) • 95.7 kB
JavaScript
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _toArray from "@babel/runtime/helpers/toArray";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _typeof from "@babel/runtime/helpers/typeof";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
/*
Created by Hassan Steven Compton.
March 7, 2024.
*/
import { useState, useEffect, useRef, useCallback } from "react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import axios from "axios";
var hudNetworkURL = "";
var hudAPIURL = "";
var hudAuth = null;
export function TermsAndConditionsPanelNavigationActivation(HUDNavigation) {
HUDNavigation('/termsandconditions');
return;
}
export function PrivacyPolicyPanelNavigationActivation(HUDNavigation) {
HUDNavigation('/privacypolicy');
return;
}
export function HomePanelNavigationActivation(HUDNavigation) {
HUDNavigation('/');
return;
}
;
export function AuthenticationPanelNavigationActivation(HUDNavigation) {
HUDNavigation('/authentication');
return;
}
;
export function AboutPanelNavigationActivation(HUDNavigation) {
HUDNavigation('/about');
return;
}
;
var ProcessIndicatorUpdater = function ProcessIndicatorUpdater(indicatorHandler, systemMessage) {
if (indicatorHandler) {
indicatorHandler(systemMessage);
return;
}
};
export function ConvertNumberToMoneyFormat(n) {
var showDecimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var minimumDecimals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
var maximumDecimals = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 2;
var moneyLocality = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "en-US";
var number = parseFloat(n);
var options = showDecimals ? {
minimumFractionDigits: minimumDecimals,
maximumFractionDigits: maximumDecimals
} : {
minimumFractionDigits: 0,
maximumFractionDigits: 0
};
var moneyNumber = n.toLocaleString(moneyLocality, options);
return moneyNumber;
}
;
export function ConvertNumberToPrecision(number) {
var decimalPlaces = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var method = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "trim";
if (typeof number !== "number") {
return number;
}
if (!["round", "floor", "ceil", "trim"].includes(method)) {
return number;
}
var factor = Math.pow(10, decimalPlaces);
if (method === "trim") {
var strNum = number.toString();
var _strNum$split = strNum.split("."),
_strNum$split2 = _slicedToArray(_strNum$split, 2),
integerPart = _strNum$split2[0],
decimalPart = _strNum$split2[1];
if (!decimalPart || decimalPlaces <= 0) {
return parseFloat(integerPart);
}
return parseFloat("".concat(integerPart, ".").concat(decimalPart.slice(0, decimalPlaces)));
}
return Math[method](number * factor) / factor;
}
;
export function ConvertNumberToScale(amounts) {
var baseN = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.05;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var _options$scalingMetho = options.scalingMethod,
scalingMethod = _options$scalingMetho === void 0 ? "divide" : _options$scalingMetho,
_options$currencySymb = options.currencySymbol,
currencySymbol = _options$currencySymb === void 0 ? "" : _options$currencySymb,
_options$format = options.format,
format = _options$format === void 0 ? false : _options$format,
_options$precision = options.precision,
precision = _options$precision === void 0 ? 2 : _options$precision,
_options$round = options.round,
round = _options$round === void 0 ? false : _options$round;
function convert(amount) {
var scaledN;
switch (scalingMethod) {
case "multiply":
scaledN = amount * baseN;
break;
case "exponential":
scaledN = Math.pow(baseN, amount);
break;
case "logarithmic":
scaledN = Math.log(amount) / Math.log(baseN);
break;
case "divide":
default:
scaledN = amount / baseN;
}
if (round) {
scaledN = Math.round(scaledN);
} else {
scaledN = parseFloat(scaledN.toFixed(precision));
}
return format ? "".concat(currencySymbol).concat(scaledN) : scaledN;
}
if (Array.isArray(amounts)) {
return amounts.map(convert);
}
return convert(amounts);
}
;
export function ConvertNumberToWords(n) {
var ones = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
var tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
if (n < 20) {
return ones[n];
}
if (n < 100) {
return tens[Math.floor(n / 10)] + (n % 10 ? '-' + ones[n % 10] : '');
}
if (n < 1000) {
return ones[Math.floor(n / 100)] + ' Hundred' + (n % 100 ? ' ' + ConvertNumberToWords(n % 100) : '');
}
var units = ["Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion"];
var unitIndex = 0;
var remainder = n;
while (remainder >= 1000) {
remainder /= 1000;
unitIndex++;
}
remainder = Math.floor(remainder);
var words = ConvertNumberToWords(remainder) + " " + units[unitIndex - 1];
var rest = n % Math.pow(1000, unitIndex);
if (rest > 0) {
words += " " + ConvertNumberToWords(rest);
}
return words;
}
;
export function ConvertToPixels(n, reference) {
if (typeof n === "string") {
var unit = n.match(/[a-z%]+$/)[0];
var number = parseFloat(n);
if (hudUniversalUnitConverters[unit]) {
return hudUniversalUnitConverters[unit](number, reference);
}
} else if (typeof n === "number" && n >= 0 && n <= 1) {
return parseFloat(n * reference);
}
return parseFloat(n);
}
;
export function ConvertFileSizeToDisplay(bytes) {
var decimalPoints = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
if (bytes === 0) return "0 Bytes";
var k = 1024;
var sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPoints)) + " " + sizes[i];
}
;
export function ConvertFileSizeToBytes(size) {
var sizeUnits = {
B: 1,
KB: 1024,
MB: Math.pow(1024, 2),
GB: Math.pow(1024, 3),
TB: Math.pow(1024, 4),
PB: Math.pow(1024, 5),
EB: Math.pow(1024, 6),
ZB: Math.pow(1024, 7),
YB: Math.pow(1024, 8)
};
var matches = size.match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB|PB|EB|ZB|YB)$/i);
if (!matches) {
console.log("Invalid file size format. Example valid formats: '5GB', '500MB', '1PB', '2.5EB'.");
return size;
}
var _matches = _slicedToArray(matches, 3),
_ = _matches[0],
value = _matches[1],
unit = _matches[2];
var nSize = parseFloat(value);
var multiplier = sizeUnits[unit.toUpperCase()];
return nSize * multiplier;
}
;
export function ConvertTextIntoParagraphs(text) {
var maxSentences = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
var maxWords = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var maxParagraphLength = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var returnArray = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var words = text.split(/\s+/);
var sentences = text.match(/[^.!?]+[.!?]+["')]*|.+/g) || [];
var paragraphs = [];
var currentParagraph = "";
var wordCount = 0;
var sentenceCount = 0;
words.forEach(function (word) {
var exceedsCharLimit = maxParagraphLength && currentParagraph.length + word.length + 1 > maxParagraphLength;
var exceedsWordLimit = maxWords && wordCount + 1 > maxWords;
var exceedsSentenceLimit = maxSentences && sentenceCount + 1 > maxSentences;
if (maxParagraphLength && exceedsCharLimit || maxWords && exceedsWordLimit || maxSentences && exceedsSentenceLimit) {
paragraphs.push(currentParagraph.trim());
currentParagraph = "";
wordCount = 0;
sentenceCount = 0;
}
currentParagraph += word + " ";
wordCount++;
if (/[.!?]$/.test(word)) {
sentenceCount++;
}
});
if (currentParagraph.trim().length > 0) {
paragraphs.push(currentParagraph.trim());
}
return returnArray ? paragraphs : paragraphs.join("\n\n");
}
;
export function ContainsBlacklistedCharacters(input) {
var whiteListedInput = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
var blacklistedChars = ' \t\n\r!@#$%^&*()+=[]{};:\'",<>/?\\|`~';
var _iterator = _createForOfIteratorHelper(whiteListedInput),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var whiteListedChar = _step.value;
blacklistedChars = blacklistedChars.replace(whiteListedChar, "");
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var blacklistedCharacters = new RegExp('[' + blacklistedChars.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&") + ']');
return blacklistedCharacters.test(input);
}
;
export function ContainsOnlyNumericCharacters(input) {
var trimmedInput = input.trim();
var regex = /^[0-9]*\.?[0-9]*$/;
return regex.test(trimmedInput);
}
;
export function ConvertSecondsToETATime(seconds) {
if (seconds === 0) {
return "0s";
}
var units = [{
name: "y",
seconds: 60 * 60 * 24 * 365
}, {
name: "mo",
seconds: 60 * 60 * 24 * 30
}, {
name: "w",
seconds: 60 * 60 * 24 * 7
}, {
name: "d",
seconds: 60 * 60 * 24
}, {
name: "h",
seconds: 60 * 60
}, {
name: "m",
seconds: 60
}, {
name: "s",
seconds: 1
}];
var remainingSeconds = seconds;
var result = "";
for (var _i = 0, _units = units; _i < _units.length; _i++) {
var unit = _units[_i];
if (remainingSeconds >= unit.seconds) {
var count = Math.floor(remainingSeconds / unit.seconds);
result += "".concat(count).concat(unit.name, " ");
remainingSeconds -= count * unit.seconds;
}
}
var milliseconds = Math.floor(remainingSeconds * 1e3);
var nanoseconds = Math.round(remainingSeconds * 1e9 % 1e6);
if (milliseconds > 0) {
result += "".concat(milliseconds, "ms ");
remainingSeconds -= milliseconds / 1e3;
}
if (nanoseconds > 0) {
result += "".concat(nanoseconds, "ns");
}
return result.trim();
}
;
export function ConvertSecondsToSubtitleTimestamp(seconds) {
var hours = Math.floor(seconds / 3600).toString().padStart(2, "0");
var minutes = Math.floor(seconds % 3600 / 60).toString().padStart(2, "0");
var secs = Math.floor(seconds % 60).toString().padStart(2, "0");
var millis = Math.round(seconds % 1 * 1000).toString().padStart(3, "0");
return "".concat(hours, ":").concat(minutes, ":").concat(secs, ",").concat(millis);
}
;
export function ConvertDuration(duration) {
var regex = /(\d+)\s*(ms|s|m|h|d|M|y|ns)/g;
var totalMilliseconds = 0;
var match;
while ((match = regex.exec(duration)) !== null) {
var value = parseInt(match[1]);
var unit = match[2];
switch (unit) {
case 'ms':
totalMilliseconds += value;
break;
case 's':
totalMilliseconds += value * 1000;
break;
case 'm':
totalMilliseconds += value * 1000 * 60;
break;
case 'h':
totalMilliseconds += value * 1000 * 60 * 60;
break;
case 'd':
totalMilliseconds += value * 1000 * 60 * 60 * 24;
break;
case 'M':
totalMilliseconds += value * 1000 * 60 * 60 * 24 * 30;
break;
case 'y':
totalMilliseconds += value * 1000 * 60 * 60 * 24 * 365;
break;
case 'ns':
totalMilliseconds += value / 1000000;
break;
default:
throw new Error("Unknown time unit: ".concat(unit));
}
}
return totalMilliseconds;
}
;
export function ConvertVideoTimeToSeconds(timeString) {
var timeParts = timeString.split(/[:hmsd]+/).filter(Boolean).map(Number).reverse();
var unitMultipliers = [1, 60, 3600, 86400, 2592000, 31536000];
return timeParts.reduce(function (total, value, index) {
return total + value * unitMultipliers[index];
}, 0);
}
;
export function ConvertTimeToSeconds(timeS) {
var timeUnitsInSeconds = {
ns: 1e-9,
ms: 1e-3,
s: 1,
m: 60,
h: 3600,
d: 86400,
w: 604800,
mo: 2629800,
y: 31557600,
dec: 315576000,
cen: 3155760000,
gen: 788940000
};
var regex = /(\d+(?:\.\d+)?)\s*(ns|ms|s|m|h|d|w|mo|y|dec|cen|gen)/gi;
var totalSeconds = 0;
var match;
while ((match = regex.exec(timeS)) !== null) {
var _match = match,
_match2 = _slicedToArray(_match, 3),
_ = _match2[0],
value = _match2[1],
unit = _match2[2];
var numericValue = parseFloat(value);
var timeM = timeUnitsInSeconds[unit];
if (!timeM) {
console.log("Unsupported time unit ~ ".concat(unit));
totalSeconds += 0;
} else if (timeM) {
totalSeconds += numericValue * timeM;
}
}
return totalSeconds;
}
;
export function ConvertPosition(value, axis) {
var rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
if (typeof value === "string") {
if (value.includes("%")) {
var percentage = parseFloat(value) / 100;
if (axis === "x") {
return percentage * window.innerWidth;
} else if (axis === "y") {
return percentage * window.innerHeight;
}
} else if (value.includes("px")) {
return parseFloat(value);
} else if (value.includes("rem")) {
return parseFloat(value) * rootFontSize;
} else if (value.includes("em")) {
return parseFloat(value) * rootFontSize;
} else if (value.includes("vw")) {
return parseFloat(value) * (window.innerWidth / 100);
} else if (value.includes("vh")) {
return parseFloat(value) * (window.innerHeight / 100);
} else if (value.includes("vmin")) {
return parseFloat(value) * (Math.min(window.innerWidth, window.innerHeight) / 100);
} else if (value.includes("vmax")) {
return parseFloat(value) * (Math.max(window.innerWidth, window.innerHeight) / 100);
}
}
return parseFloat(value);
}
;
export function ConvertToReadableDuration(ms) {
var years = Math.floor(ms / (1000 * 60 * 60 * 24 * 365));
ms %= 1000 * 60 * 60 * 24 * 365;
var months = Math.floor(ms / (1000 * 60 * 60 * 24 * 30));
ms %= 1000 * 60 * 60 * 24 * 30;
var days = Math.floor(ms / (1000 * 60 * 60 * 24));
ms %= 1000 * 60 * 60 * 24;
var hours = Math.floor(ms / (1000 * 60 * 60));
ms %= 1000 * 60 * 60;
var minutes = Math.floor(ms / (1000 * 60));
ms %= 1000 * 60;
var seconds = Math.floor(ms / 1000);
ms %= 1000;
return {
years: years,
months: months,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: ms
};
}
;
export function ConvertToSizeUnits(size) {
var units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
var unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return {
current: size.toFixed(2),
unit: units[unitIndex]
};
}
;
export function ConvertSizeToDistanceInFeet() {
var boxWidthPixels = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
var canvasWidthPixels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1920;
var diagonalInches = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 17;
var screenHeightPixels = window.screen.height * window.devicePixelRatio;
var screenWidthPixels = window.screen.width * window.devicePixelRatio;
var diagonalPixels = Math.sqrt(Math.pow(screenWidthPixels, 2) + Math.pow(screenHeightPixels, 2));
var ppi = diagonalPixels / diagonalInches;
var inchesPerPixel = 1 / ppi;
var feetPerPixel = inchesPerPixel / 12;
var pixelDistance = canvasWidthPixels / boxWidthPixels * canvasWidthPixels;
return pixelDistance * feetPerPixel;
}
;
export function ConvertURLToIP(url) {
try {
var parsedUrl = new URL(url);
return parsedUrl.hostname;
} catch (error) {
console.error("Invalid URL ~ ", error);
return null;
}
}
;
export function Countdown(duration, callback, updateDisplay) {
var numericTimeRemaining = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var _useState = useState(ConvertDuration(duration)),
_useState2 = _slicedToArray(_useState, 2),
remainingTime = _useState2[0],
setRemainingTime = _useState2[1];
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
completed = _useState4[0],
setCompleted = _useState4[1];
var callbackRef = useRef(callback);
var intervalId = useRef(null);
var startCountdown = useCallback(function () {
setCompleted(false);
clearInterval(intervalId.current);
var time = ConvertDuration(duration);
setRemainingTime(time);
intervalId.current = setInterval(function () {
time -= 1000;
updateDisplay(numericTimeRemaining ? time : ConvertToReadableDuration(time));
setRemainingTime(time);
if (time <= 0) {
clearInterval(intervalId.current);
setRemainingTime(0);
setCompleted(true);
if (callbackRef.current) {
callbackRef.current();
}
}
}, 1000);
updateDisplay(numericTimeRemaining ? time : ConvertToReadableDuration(time));
}, [duration]);
var stopCountdown = useCallback(function () {
clearInterval(intervalId.current);
}, []);
var resetCountdown = useCallback(function () {
stopCountdown();
setRemainingTime(ConvertDuration(duration));
setCompleted(false);
}, [duration, stopCountdown]);
useEffect(function () {
callbackRef.current = callback;
}, [callback]);
useEffect(function () {
return function () {
clearInterval(intervalId.current);
};
}, []);
return {
remainingTime: numericTimeRemaining ? remainingTime : ConvertToReadableDuration(remainingTime),
completed: completed,
startCountdown: startCountdown,
stopCountdown: stopCountdown,
resetCountdown: resetCountdown
};
}
;
export function ConvertToVideoTime(time) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var baseOptions = {
showYears: false,
showMonths: false,
showDays: true,
showHours: true,
showMinutes: true,
showSeconds: true,
showMilliseconds: false,
useLetters: false,
leadingZero: true,
showZero: true
};
var mergedOptions = _objectSpread(_objectSpread({}, baseOptions), options);
var showYears = mergedOptions.showYears,
showMonths = mergedOptions.showMonths,
showDays = mergedOptions.showDays,
showHours = mergedOptions.showHours,
showMinutes = mergedOptions.showMinutes,
showSeconds = mergedOptions.showSeconds,
showMilliseconds = mergedOptions.showMilliseconds,
useLetters = mergedOptions.useLetters,
leadingZero = mergedOptions.leadingZero,
showZero = mergedOptions.showZero;
var years = Math.floor(time / (365 * 24 * 60 * 60));
var months = Math.floor(time % (365 * 24 * 60 * 60) / (30 * 24 * 60 * 60));
var days = Math.floor(time % (30 * 24 * 60 * 60) / (24 * 60 * 60));
var hours = Math.floor(time % (24 * 60 * 60) / (60 * 60));
var minutes = Math.floor(time % (60 * 60) / 60);
var seconds = Math.floor(time % 60);
var milliseconds = Math.round(time % 1 * 1000);
var formattedTime = "";
if (years > 0 && showYears) {
formattedTime = "".concat(years).concat(useLetters ? "y:" : ":").concat(months).concat(useLetters ? "m:" : ":").concat(days).concat(useLetters ? "d:" : ":").concat(hours < 10 && leadingZero ? "0" : "").concat(hours).concat(useLetters ? "h:" : ":").concat(minutes < 10 ? "0" : "").concat(minutes).concat(useLetters ? "m:" : ":").concat(seconds < 10 ? "0" : "").concat(seconds).concat(useLetters ? "s" : "");
} else if (months > 0 && showMonths) {
formattedTime = "".concat(months).concat(useLetters ? "m:" : ":").concat(days).concat(useLetters ? "d:" : ":").concat(hours < 10 && leadingZero ? "0" : "").concat(hours).concat(useLetters ? "h:" : ":").concat(minutes < 10 ? "0" : "").concat(minutes).concat(useLetters ? "m:" : ":").concat(seconds < 10 ? "0" : "").concat(seconds).concat(useLetters ? "s" : "");
} else if (days > 0 && showDays) {
formattedTime = "".concat(days).concat(useLetters ? "d:" : ":").concat(hours < 10 && leadingZero ? "0" : "").concat(hours).concat(useLetters ? "h:" : ":").concat(minutes < 10 ? "0" : "").concat(minutes).concat(useLetters ? "m:" : ":").concat(seconds < 10 ? "0" : "").concat(seconds).concat(useLetters ? "s" : "");
} else if (hours > 0 && showHours) {
formattedTime = "".concat(hours < 10 && leadingZero ? "0" : "").concat(hours).concat(useLetters ? "h:" : ":").concat(minutes < 10 ? "0" : "").concat(minutes).concat(useLetters ? "m:" : ":").concat(seconds < 10 ? "0" : "").concat(seconds).concat(useLetters ? "s" : "");
} else if (minutes > 0 || showZero && showMinutes) {
formattedTime = "".concat(minutes, ":").concat(seconds < 10 ? "0" : "").concat(seconds);
} else {
formattedTime = "".concat(seconds < 10 ? "0" : "").concat(seconds);
}
if (showMilliseconds && milliseconds > 0) {
formattedTime += useLetters ? "".concat(milliseconds, "ms") : ".".concat(milliseconds);
}
return formattedTime;
}
;
export function ConvertDateTime(dateString) {
var includeTimeZone = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var includeLeadingZeroHour = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var includeSeconds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var shortDateFormat = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var includeLeadingZeroMonth = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
var includeTime = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : true;
var date = new Date(dateString);
var formattedDate;
if (shortDateFormat) {
formattedDate = date.toLocaleDateString("en-US", {
month: includeLeadingZeroMonth ? "2-digit" : "numeric",
day: "2-digit",
year: "numeric"
});
} else {
formattedDate = date.toLocaleDateString("en-US", {
weekday: "short",
month: "short",
day: "numeric",
year: "numeric"
});
}
var timeOptions = {
hour: includeLeadingZeroHour ? "2-digit" : "numeric",
minute: "2-digit",
hour12: true
};
if (includeSeconds) {
timeOptions.second = "2-digit";
}
var finalOutput = formattedDate;
if (includeTime) {
var formattedTime = date.toLocaleTimeString("en-US", timeOptions);
finalOutput += " ".concat(formattedTime);
}
if (includeTimeZone) {
var timeZone = date.toTimeString().match(/\(([^)]+)\)/)[1];
finalOutput += " (".concat(timeZone, ")");
}
return finalOutput;
}
;
export function DisplayLegalDocumentCurrentDate() {
var date = new Date();
var month = date.toLocaleString("default", {
month: "long"
});
var year = date.getFullYear();
var day = date.getDate();
return "".concat(month, " ").concat(day, ", ").concat(year);
}
;
export function DetermineDateDifference(previousDate) {
var currentDate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date();
var unit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "seconds";
var precision = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var roundingMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "floor";
var roundTo = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : "none";
var previous = new Date(previousDate);
var current = new Date(currentDate);
if (roundTo === "start") {
previous.setHours(0, 0, 0, 0);
current.setHours(0, 0, 0, 0);
} else if (roundTo === "end") {
previous.setHours(23, 59, 59, 999);
current.setHours(23, 59, 59, 999);
}
var diffInMilliseconds = current - previous;
var conversions = {
days: 1000 * 60 * 60 * 24,
hours: 1000 * 60 * 60,
minutes: 1000 * 60,
seconds: 1000
};
var value = diffInMilliseconds / conversions[unit];
var result;
if (precision === 0) {
result = roundingMethod === "round" ? Math.round(value) : Math.floor(value);
} else {
result = value.toFixed(precision);
}
return result;
}
;
export function DetermineBrowser() {
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var userAgent = navigator.userAgent;
var usingBrave = navigator.brave && typeof navigator.brave.isBrave === "function";
var browser = "Unknown Browser";
if (userAgent.includes("Vivaldi")) {
browser = "Vivaldi";
} else if (usingBrave) {
browser = "Brave";
} else if (userAgent.includes("OPR") || userAgent.includes("Opera")) {
browser = "Opera";
} else if (userAgent.includes("Edg")) {
browser = "Edge";
} else if (userAgent.includes("Chrome")) {
browser = "Chrome";
} else if (userAgent.includes("Firefox")) {
browser = "Firefox";
} else if (userAgent.includes("Safari")) {
browser = "Safari";
} else if (userAgent.includes("MSIE") || userAgent.includes("Trident")) {
browser = "Internet Explorer";
}
var usingTor = typeof window !== "undefined" && (navigator.userAgent.includes("Tor") || navigator.connection && navigator.connection.type === "none" || window.screen.width === 1000);
if (usingTor) {
browser = "Tor";
}
if (target) {
return browser === target;
}
return browser;
}
;
export function DownloadFile(content) {
var filename = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "file.txt";
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "text/plain";
var blob = new Blob([content], {
type: type
});
var link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
return;
}
;
export function DownloadTwoPagePDF(firstPageContent, backPageContent, fileName) {
var orientation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '1';
var format = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'a4';
try {
html2canvas(firstPageContent).then(function (firstCanvas) {
var imgData = firstCanvas.toDataURL("image/png");
var pdf = new jsPDF({
orientation: orientation === "1" ? "l" : "p",
unit: 'mm',
format: 'a4'
});
var pdfHeight = pdf.internal.pageSize.getHeight();
var pdfWidth = pdf.internal.pageSize.getWidth();
var imgHeight = firstCanvas.height * pdfWidth / firstCanvas.width;
var imgWidth = pdfWidth;
if (imgHeight > pdfHeight) {
imgWidth = firstCanvas.width * pdfHeight / firstCanvas.height;
imgHeight = pdfHeight;
}
var y = (pdfHeight - imgHeight) / 2;
var x = (pdfWidth - imgWidth) / 2;
pdf.addImage(imgData, 'PNG', x, y, imgWidth, imgHeight);
html2canvas(backPageContent).then(function (backCanvas) {
var backImageData = backCanvas.toDataURL("image/png");
var backImgHeight = backCanvas.height * pdfWidth / backCanvas.width;
var backImgWidth = pdfWidth;
pdf.addPage({
format: format,
orientation: orientation === "1" ? "l" : "p"
});
var backY = (pdfHeight - backImgHeight) / 2;
var backX = (pdfWidth - backImgWidth) / 2;
pdf.addImage(backImageData, "PNG", backX, backY, backImgWidth, backImgHeight);
pdf.save("".concat(fileName, ".pdf"));
return true;
})["catch"](function (error) {
console.error("Did not convert back page to PDF: ", error);
});
return true;
})["catch"](function (error) {
console.error("Did not convert front page to PDF: ", error);
});
} catch (error) {
return false;
}
}
;
export function DownloadPDF(contentRef, fileName) {
try {
html2canvas(contentRef.current).then(function (canvas) {
var imgData = canvas.toDataURL("image/png");
var pdf = new jsPDF({
orientation: "p",
unit: "mm",
format: "a4"
});
var pdfHeight = pdf.internal.pageSize.getHeight();
var pdfWidth = pdf.internal.pageSize.getWidth();
var imgHeight = canvas.height * pdfWidth / canvas.width;
var imgWidth = pdfWidth;
if (imgHeight > pdfHeight) {
imgWidth = canvas.width * pdfHeight / canvas.height;
imgHeight = pdfHeight;
}
var y = (pdfHeight - imgHeight) / 2;
var x = (pdfWidth - imgWidth) / 2;
pdf.addImage(imgData, 'PNG', x, y, imgWidth, imgHeight);
pdf.save("".concat(fileName, ".pdf"));
return true;
})["catch"](function (error) {
console.error("Did not convert to PDF: ", error);
});
} catch (error) {
return false;
}
}
;
export function DeepEqualData(currentData, data) {
var visited = new WeakSet();
function equal(current, other) {
if (current === other) {
return true;
}
if (current == null || other == null || _typeof(current) !== "object" || _typeof(other) !== "object") {
return false;
}
if (visited.has(current) || visited.has(other)) {
return true;
}
visited.add(current);
visited.add(other);
if (Array.isArray(current) !== Array.isArray(other)) {
return false;
}
var currentKeys = Object.keys(current);
var otherKeys = Object.keys(other);
if (currentKeys.length !== otherKeys.length) {
return false;
}
for (var _i2 = 0, _currentKeys = currentKeys; _i2 < _currentKeys.length; _i2++) {
var key = _currentKeys[_i2];
if (!otherKeys.includes(key) || !equal(current[key], other[key])) {
return false;
}
}
return true;
}
return equal(currentData, data);
}
;
export function DeepCloneData(data) {
return JSON.parse(JSON.stringify(data));
}
;
export function MergeJSON(data1, data2) {
var propertyRules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var copy1 = JSON.parse(JSON.stringify(data1));
var copy2 = JSON.parse(JSON.stringify(data2));
function getMatchingRule(path) {
for (var rule in propertyRules) {
var regexPattern = "^" + rule.replace(/\[\*\]/g, "\\[\\d+\\]") + "$";
if (new RegExp(regexPattern).test(path)) {
return rule;
}
}
return null;
}
function deepMerge(obj1, obj2) {
var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
if (Array.isArray(obj1) && Array.isArray(obj2)) {
return obj1.map(function (item, index) {
var newPath = "".concat(path, "[").concat(index, "]");
return deepMerge(item, obj2[index] || {}, newPath);
});
} else if (_typeof(obj1) === "object" && obj1 !== null && _typeof(obj2) === "object" && obj2 !== null) {
var merged = {};
var _iterator2 = _createForOfIteratorHelper(new Set([].concat(_toConsumableArray(Object.keys(obj1)), _toConsumableArray(Object.keys(obj2))))),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var key = _step2.value;
var newPath = path ? "".concat(path, ".").concat(key) : key;
var matchedRule = getMatchingRule(newPath);
if (matchedRule) {
merged[key] = propertyRules[matchedRule](obj1[key], obj2[key]);
} else if (propertyRules[newPath]) {
merged[key] = propertyRules[newPath](obj1[key], obj2[key]);
} else {
merged[key] = deepMerge(obj1[key], obj2[key], newPath);
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return merged;
}
return obj2 !== undefined ? obj2 : obj1;
}
return deepMerge(copy1, copy2);
}
;
export function UpdateObject(obj, keyPath, value) {
var pathArray = Array.isArray(keyPath) ? keyPath : keyPath.split(".");
var updateRecursive = function updateRecursive(currentObj, currentPath) {
var _currentPath = _toArray(currentPath),
key = _currentPath[0],
remainingPath = _currentPath.slice(1);
if (remainingPath.length === 0) {
return _objectSpread(_objectSpread({}, currentObj), {}, _defineProperty({}, key, value));
}
return _objectSpread(_objectSpread({}, currentObj), {}, _defineProperty({}, key, updateRecursive(currentObj[key] || {}, remainingPath)));
};
return updateRecursive(obj, pathArray);
}
;
export function FilterNullProperties(data) {
return Object.fromEntries(Object.entries(data).filter(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
return value !== null;
}));
}
;
export function PurifyData(data) {
var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref3$validate = _ref3.validate,
validate = _ref3$validate === void 0 ? [] : _ref3$validate,
_ref3$sanitize = _ref3.sanitize,
sanitize = _ref3$sanitize === void 0 ? [] : _ref3$sanitize,
_ref3$onError = _ref3.onError,
onError = _ref3$onError === void 0 ? function (error) {
throw error;
} : _ref3$onError;
try {
data = Guard(data, {
validate: validate
});
var _iterator3 = _createForOfIteratorHelper(sanitize),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var sanitizer = _step3.value;
data = sanitizer(data);
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
return data;
} catch (error) {
onError(error);
return null;
}
}
;
export function Guard(data) {
var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref4$validate = _ref4.validate,
validate = _ref4$validate === void 0 ? [] : _ref4$validate,
_ref4$onError = _ref4.onError,
onError = _ref4$onError === void 0 ? function (error) {
throw error;
} : _ref4$onError;
try {
var _iterator4 = _createForOfIteratorHelper(validate),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var _step4$value = _slicedToArray(_step4.value, 2),
rule = _step4$value[0],
message = _step4$value[1];
if (!rule(data)) {
throw new Error(message || "Restricted data detected.");
}
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
return data;
} catch (error) {
onError(error);
return null;
}
}
;
export function WaitForComponent(_x) {
return _WaitForComponent.apply(this, arguments);
}
function _WaitForComponent() {
_WaitForComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(componentRef) {
var timeout,
start,
_args11 = arguments;
return _regeneratorRuntime.wrap(function _callee11$(_context11) {
while (1) switch (_context11.prev = _context11.next) {
case 0:
timeout = _args11.length > 1 && _args11[1] !== undefined ? _args11[1] : 5000;
start = performance.now();
return _context11.abrupt("return", new Promise(function (resolve, reject) {
function check() {
if (componentRef.current !== null) {
return resolve(componentRef.current);
}
if (performance.now() - start >= timeout) {
return resolve(null);
}
requestAnimationFrame(check);
}
;
check();
}));
case 3:
case "end":
return _context11.stop();
}
}, _callee11);
}));
return _WaitForComponent.apply(this, arguments);
}
;
export function WaitForData(inputData, conditions) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var defaultOptions = {
interval: 100,
timeout: 5000,
onTimeout: function onTimeout() {
throw new Error("Awaiting timed out.");
},
mode: "all"
};
var settings = _objectSpread(_objectSpread({}, defaultOptions), options);
return new Promise(function (resolve, reject) {
var startTime = Date.now();
var staticData = typeof inputData !== "function";
var getData = function getData() {
return staticData ? inputData : inputData();
};
var evaluateConditions = function evaluateConditions(data) {
return conditions.map(function (condition) {
return typeof condition === "function" ? condition(data) : data === condition;
});
};
var poll = function poll() {
try {
var data = getData();
var results = evaluateConditions(data);
var satisfied = settings.mode === "all" ? results.every(Boolean) : results.some(Boolean);
if (satisfied) {
resolve({
data: data,
results: results
});
} else if (Date.now() - startTime > settings.timeout) {
reject(settings.onTimeout());
} else {
setTimeout(poll, settings.interval);
}
} catch (error) {
reject(error);
}
};
poll();
});
}
;
export function AsyncAction(executor) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var canceled = false;
var defaultOptions = {
onCancel: function onCancel() {},
onSuccess: function onSuccess() {},
onError: function onError() {},
onFinally: function onFinally() {},
onStageChange: function onStageChange() {},
trackState: false
};
var settings = _objectSpread(_objectSpread({}, defaultOptions), options);
var state = {
inProgress: false,
canceled: canceled,
completed: false,
currentStage: null,
progress: 0
};
var updateStage = function updateStage(stage) {
if (settings.trackState) {
state.currentStage = stage;
if (settings.stages && settings.stages.length > 0) {
var stageIndex = settings.stages.indexOf(stage);
state.progress = stageIndex >= 0 ? (stageIndex + 1) / settings.stages.length * 100 : state.progress;
}
settings.onStageChange(_objectSpread({}, state));
}
};
var action = /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var _len,
args,
_key,
result,
_args = arguments;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (!canceled) {
_context.next = 3;
break;
}
settings.onCancel();
return _context.abrupt("return");
case 3:
if (settings.trackState) {
state.inProgress = true;
state.canceled = canceled;
state.completed = false;
}
_context.prev = 4;
for (_len = _args.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = _args[_key];
}
_context.next = 8;
return executor.apply(void 0, args.concat([updateStage]));
case 8:
result = _context.sent;
if (!canceled) {
settings.onSuccess(result);
if (settings.trackState) {
state.completed = true;
state.currentStage = null;
state.progress = 100;
}
}
return _context.abrupt("return", result);
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](4);
if (!canceled) {
settings.onError(_context.t0);
if (settings.trackState) {
state.completed = true;
}
}
throw _context.t0;
case 17:
_context.prev = 17;
if (!canceled) {
settings.onFinally();
if (settings.trackState) {
state.inProgress = false;
}
}
return _context.finish(17);
case 20:
case "end":
return _context.stop();
}
}, _callee, null, [[4, 13, 17, 20]]);
}));
return function action() {
return _ref5.apply(this, arguments);
};
}();
action.cancel = function () {
canceled = true;
if (settings.trackState) {
state.canceled = true;
state.inProgress = false;
state.currentStage = null;
}
settings.onCancel();
};
action.reset = function () {
canceled = false;
if (settings.trackState) {
state.canceled = false;
state.completed = false;
state.currentStage = null;
state.progress = 0;
}
};
action.getState = function () {
if (!settings.trackState) {
return null;
}
return _objectSpread({}, state);
};
return action;
}
;
export function Debounce(func, wait) {
var immediate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var timeout;
var debounced = function debounced() {
var _this = this;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return func.apply(_this, args);
case 3:
_context2.next = 8;
break;
case 5:
_context2.prev = 5;
_context2.t0 = _context2["catch"](0);
if (_context2.t0.type !== "cancelation") {
console.error("Error during debounce ~ ", _context2.t0);
}
case 8:
timeout = null;
case 9:
case "end":
return _context2.stop();
}
}, _callee2, null, [[0, 5]]);
})), wait);
};
if (immediate) {
debounced();
}
return debounced;
}
;
export function Delay(ms) {
return new Promise(function (resolve) {
return setTimeout(resolve, ms);
});
}
;
export function ConvertComponentToTwoPDFData(_x2, _x3, _x4) {
return _ConvertComponentToTwoPDFData.apply(this, arguments);
}
function _ConvertComponentToTwoPDFData() {
_ConvertComponentToTwoPDFData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(firstPageContent, backPageContent, fileName) {
var orientation,
format,
_args12 = arguments;
return _regeneratorRuntime.wrap(function _callee12$(_context12) {
while (1) switch (_context12.prev = _context12.next) {
case 0:
orientation = _args12.length > 3 && _args12[3] !== undefined ? _args12[3] : '1';
format = _args12.length > 4 && _args12[4] !== undefined ? _args12[4] : 'a4';
return _context12.abrupt("return", new Promise(function (resolve, reject) {
try {
html2canvas(firstPageContent).then(function (firstCanvas) {
var imgData = firstCanvas.toDataURL("image/png");
var pdf = new jsPDF({
orientation: orientation === "1" ? "l" : "p",
unit: 'mm',
format: 'a4'
});
var pdfHeight = pdf.internal.pageSize.getHeight();
var pdfWidth = pdf.internal.pageSize.getWidth();
var imgHeight = firstCanvas.height * pdfWidth / firstCanvas.width;
var imgWidth = pdfWidth;
if (imgHeight > pdfHeight) {
imgWidth = firstCanvas.width * pdfHeight / firstCanvas.height;
imgHeight = pdfHeight;
}
var y = (pdfHeight - imgHeight) / 2;
var x = (pdfWidth - imgWidth) / 2;
pdf.addImage(imgData, 'PNG', x, y, imgWidth, imgHeight);
html2canvas(backPageContent).then(function (backCanvas) {
var backImageData = backCanvas.toDataURL("image/png");
var backImgHeight = backCanvas.height * pdfWidth / backCanvas.width;
var backImgWidth = pdfWidth;
pdf.addPage({
format: format,
orientation: orientation === "1" ? "l" : "p"
});
var backY = (pdfHeight - backImgHeight) / 2;
var backX = (pdfWidth - backImgWidth) / 2;
pdf.addImage(backImageData, "PNG", backX, backY, backImgWidth, backImgHeight);
var componentPDFData = pdf.output("datauristring").split(';base64,')[1];
resolve(componentPDFData);
})["catch"](function (error) {
console.error("Did not convert back page to PDF: ", error);
});
return true;
})["catch"](function (error) {
console.error("Did not convert front page to PDF: ", error);
});
} catch (error) {
return false;
}
}));
case 3:
case "end":
return _context12.stop();
}
}, _callee12);
}));
return _ConvertComponentToTwoPDFData.apply(this, arguments);
}
;
export function ConvertComponentToPDFData(_x5, _x6) {
return _ConvertComponentToPDFData.apply(this, arguments);
}
function _ConvertComponentToPDFData() {
_ConvertComponentToPDFData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(contentRef, fileName) {
return _regeneratorRuntime.wrap(function _callee13$(_context13) {
while (1) switch (_context13.prev = _context13.next) {
case 0:
return _context13.abrupt("return", new Promise(function (resolve, reject) {
try {
html2canvas(contentRef.current).then(function (canvas) {
var imgData = canvas.toDataURL("image/png");
var pdf = new jsPDF({
orientation: "p",
unit: "px",
format: [canvas.width, canvas.height]
});
pdf.addImage(imgData, "PNG", 0, 0);
var componentPDFData = pdf.output("datauristring").split(';base64,')[1];
resolve(componentPDFData);
})["catch"](function (error) {
console.error("Did not convert component to PDF data: ", error);
reject(error);
});
} catch (error) {
reject(error);
}
}));
case 1:
case "end":
return _context13.stop();