@trap_stevo/legendarybuilderproreact-ui
Version:
The legendary UI & utility API that makes your application a legendary application. ~ Created by Steven Compton
1,339 lines (1,336 loc) • 118 kB
JavaScript
import _toArray from "@babel/runtime/helpers/toArray";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _typeof from "@babel/runtime/helpers/typeof";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
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 { unzipSync } from "fflate";
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 ConvertNumberToSafeNumber(n, fallback) {
var min = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -Infinity;
var max = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Infinity;
var parsed = typeof n === "number" ? n : parseFloat(n);
if (isNaN(parsed)) {
return fallback;
}
return Math.min(max, Math.max(min, parsed));
}
;
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 ConvertFileSizeToUnit(sizeString) {
var targetUnit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "MB";
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 match = sizeString.match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB|PB|EB|ZB|YB)$/i);
if (!match) {
console.warn("Invalid file size format. Example valid formats ~ 'GB', 'MB', 'PB', 'EB'.");
return NaN;
}
var _match = _slicedToArray(match, 3),
_ = _match[0],
value = _match[1],
unit = _match[2];
var fromUnit = unit.toUpperCase();
var toUnit = targetUnit.toUpperCase();
if (!(fromUnit in sizeUnits) || !(toUnit in sizeUnits)) {
console.warn("Invalid conversion units ~", fromUnit, toUnit);
return NaN;
}
var valueInBytes = parseFloat(value) * sizeUnits[fromUnit];
var converted = valueInBytes / sizeUnits[toUnit];
return converted;
}
;
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.warn("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 ConvertMillisecondsToETATime(ms) {
if (ms === 0) {
return "0s";
}
var units = [{
name: "mil",
ms: 1000 * 60 * 60 * 24 * 365 * 1000
}, {
name: "cen",
ms: 1000 * 60 * 60 * 24 * 365 * 100
}, {
name: "dec",
ms: 1000 * 60 * 60 * 24 * 365 * 10
}, {
name: "y",
ms: 1000 * 60 * 60 * 24 * 365
}, {
name: "mo",
ms: 1000 * 60 * 60 * 24 * 30
}, {
name: "w",
ms: 1000 * 60 * 60 * 24 * 7
}, {
name: "d",
ms: 1000 * 60 * 60 * 24
}, {
name: "h",
ms: 1000 * 60 * 60
}, {
name: "m",
ms: 1000 * 60
}, {
name: "s",
ms: 1000
}];
var remainingMs = ms;
var result = "";
for (var _i = 0, _units = units; _i < _units.length; _i++) {
var unit = _units[_i];
if (remainingMs >= unit.ms) {
var count = Math.floor(remainingMs / unit.ms);
result += "".concat(count).concat(unit.name, " ");
remainingMs -= count * unit.ms;
}
}
var wholeMilliseconds = Math.floor(remainingMs);
var remainingFraction = remainingMs - wholeMilliseconds;
if (wholeMilliseconds > 0) {
result += "".concat(wholeMilliseconds, "ms ");
}
var nanoseconds = Math.round(remainingFraction * 1e6);
if (nanoseconds > 0) {
result += "".concat(nanoseconds, "ns");
}
return result.trim();
}
;
export function ConvertSecondsToETATime(seconds) {
if (seconds === 0) {
return "0s";
}
var units = [{
name: "mil",
ms: 60 * 60 * 24 * 365 * 1000
}, {
name: "cen",
ms: 60 * 60 * 24 * 365 * 100
}, {
name: "dec",
ms: 60 * 60 * 24 * 365 * 10
}, {
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 _i2 = 0, _units2 = units; _i2 < _units2.length; _i2++) {
var unit = _units2[_i2];
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 ConvertTimeToTimeUnit(timeS) {
var convertToUnit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "s";
var timeUnitsInSeconds = {
ns: 1e-9,
ms: 1e-3,
s: 1,
m: 60,
h: 3600,
d: 86400,
w: 604800,
mo: 2629800,
y: 31557600,
dec: 315576000,
gen: 788940000,
cen: 3155760000
};
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 _match2 = match,
_match3 = _slicedToArray(_match2, 3),
_ = _match3[0],
value = _match3[1],
unitRaw = _match3[2];
var unit = unitRaw.toLowerCase();
var numericValue = parseFloat(value);
var unitInSeconds = timeUnitsInSeconds[unit];
if (!unitInSeconds) {
console.log("Unsupported time unit ~ ".concat(unit));
continue;
}
totalSeconds += numericValue * unitInSeconds;
}
var targetUnitInSeconds = timeUnitsInSeconds[convertToUnit];
if (!targetUnitInSeconds) {
return 0;
}
return totalSeconds / targetUnitInSeconds;
}
;
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,
gen: 788940000,
cen: 3155760000
};
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 _match4 = match,
_match5 = _slicedToArray(_match4, 3),
_ = _match5[0],
value = _match5[1],
unitRaw = _match5[2];
var unit = unitRaw.toLowerCase();
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 ConvertPathsToArchiveTree(paths) {
var root = [];
var _iterator2 = _createForOfIteratorHelper(paths),
_step2;
try {
var _loop = function _loop() {
var path = _step2.value;
var cleanPath = path.replace(/\/+$/, "");
var segments = cleanPath.split("/").filter(Boolean);
var currentLevel = root;
segments.forEach(function (segment, index) {
var trailingEntry = index === segments.length - 1;
var file = !path.endsWith("/") && trailingEntry;
var existing = currentLevel.find(function (item) {
return item.name === segment;
});
if (!existing) {
existing = {
name: segment,
type: file ? "file" : "folder",
children: []
};
currentLevel.push(existing);
}
currentLevel = existing.children;
});
};
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
_loop();
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return root;
}
;
export function ConvertURLToIP(url) {
try {
var parsedUrl = new URL(url);
return parsedUrl.hostname;
} catch (error) {
console.error("Invalid URL ~ ", error);
return null;
}
}
;
export function ClassifyURL(input) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$allowedProtocols = _ref.allowedProtocols,
allowedProtocols = _ref$allowedProtocols === void 0 ? ["https:"] : _ref$allowedProtocols,
_ref$allowedDomains = _ref.allowedDomains,
allowedDomains = _ref$allowedDomains === void 0 ? null : _ref$allowedDomains,
_ref$blockedDomains = _ref.blockedDomains,
blockedDomains = _ref$blockedDomains === void 0 ? null : _ref$blockedDomains,
_ref$blockedKeywords = _ref.blockedKeywords,
blockedKeywords = _ref$blockedKeywords === void 0 ? [] : _ref$blockedKeywords,
_ref$domainHandlers = _ref.domainHandlers,
domainHandlers = _ref$domainHandlers === void 0 ? {} : _ref$domainHandlers,
_ref$regexPatterns = _ref.regexPatterns,
regexPatterns = _ref$regexPatterns === void 0 ? [] : _ref$regexPatterns;
var result = {
originalInput: input,
reasonCode: "not-a-url",
allowed: false,
valid: false,
domain: null,
type: null
};
var basicURLPattern = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s/$.?#].[^\s]*$/i;
if (!basicURLPattern.test(input)) {
return result;
}
try {
var url = new URL(input);
var protocol = url.protocol;
var hostname = url.hostname;
var fullURL = url.href;
var comparisonHost = hostname.toLowerCase();
var comparisonURL = fullURL.toLowerCase();
result.reasonCode = "none";
result.domain = hostname;
result.valid = true;
if (!allowedProtocols.includes(protocol)) {
result.reasonCode = "invalid-protocol";
return result;
}
if (blockedKeywords.some(function (keyword) {
return comparisonURL.includes(keyword);
})) {
result.reasonCode = "blocked-keyword";
return result;
}
if (blockedDomains && blockedDomains.some(function (domain) {
return comparisonHost.includes(domain);
})) {
result.reasonCode = "blocked-domain";
return result;
}
if (allowedDomains && !allowedDomains.some(function (domain) {
return comparisonHost.includes(domain);
})) {
result.reasonCode = "restricted-domain";
return result;
}
if (regexPatterns.length > 0) {
var matchesPattern = regexPatterns.some(function (pattern) {
return new RegExp(pattern).test(input);
});
if (!matchesPattern) {
result.reasonCode = "regex-mismatch";
return result;
}
}
var domainHandler = Object.entries(domainHandlers).find(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 1),
domain = _ref3[0];
return comparisonHost.includes(domain);
});
if (domainHandler) {
var _domainHandler = _slicedToArray(domainHandler, 2),
handlerFn = _domainHandler[1];
if (typeof handlerFn === "function") {
var handlerResult = handlerFn(url);
if (!handlerResult) {
result.reasonCode = "handler-rejected";
return result;
}
result.type = handlerResult.type || null;
}
}
result.allowed = true;
} catch (error) {
result.reasonCode = "not-a-url";
}
return result;
}
;
export function SecuredURL(input) {
var allowedSecureProtocols = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ["https:", "wss:", "ftps:", "sftp:", "ipfs:", "dat:", "hyper:"];
try {
var url = new URL(input);
return allowedSecureProtocols.includes(url.protocol);
} catch (_unused) {
return false;
}
}
;
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 ConvertDateToDateAge(date) {
var thresholds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "8h";
var now = Date.now();
var inputTime = new Date(date).getTime();
var ageMS = now - inputTime;
var results = [];
var thresholdArray = Array.isArray(thresholds) ? thresholds : [thresholds];
var _iterator3 = _createForOfIteratorHelper(thresholdArray),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var t = _step3.value;
try {
var thresholdMS = ConvertTimeToTimeUnit(t, "ms");
var thresholdUnitMatch = t.match(/(ns|ms|s|m|h|d|w|mo|y|dec|cen|gen)\s*$/i);
var unit = thresholdUnitMatch ? thresholdUnitMatch[1] : "ms";
results.push({
older: ageMS > thresholdMS,
unit: unit,
age: ConvertTimeToTimeUnit("".concat(ageMS, "ms"), unit),
threshold: t
});
} catch (error) {}
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
return results.length === 1 ? results[0] : results;
}
;
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 DownloadFileFromURL(_x) {
return _DownloadFileFromURL.apply(this, arguments);
}
function _DownloadFileFromURL() {
_DownloadFileFromURL = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(url) {
var filename,
forceDownload,
mime,
anchor,
forcedURL,
response,
blob,
link,
blobURL,
_args11 = arguments;
return _regeneratorRuntime.wrap(function _callee11$(_context11) {
while (1) switch (_context11.prev = _context11.next) {
case 0:
filename = _args11.length > 1 && _args11[1] !== undefined ? _args11[1] : "file";
forceDownload = _args11.length > 2 && _args11[2] !== undefined ? _args11[2] : false;
mime = _args11.length > 3 && _args11[3] !== undefined ? _args11[3] : "application/octet-stream";
if (!forceDownload) {
_context11.next = 15;
break;
}
anchor = document.createElement("a");
forcedURL = "".concat(url).concat(url.includes("?") ? "&" : "?", "response-content-disposition=attachment");
anchor.href = forcedURL;
anchor.download = filename;
anchor.target = "_blank";
anchor.rel = "noopener noreferrer";
anchor.style.display = "none";
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
return _context11.abrupt("return", true);
case 15:
_context11.prev = 15;
_context11.next = 18;
return fetch(url);
case 18:
response = _context11.sent;
if (response.ok) {
_context11.next = 21;
break;
}
throw new Error("Did not download file ~ ".concat(response.status, " ").concat(response.statusText));
case 21:
_context11.next = 23;
return response.blob();
case 23:
blob = _context11.sent;
link = document.createElement("a");
blobURL = URL.createObjectURL(blob);
link.href = blobURL;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(blobURL);
return _context11.abrupt("return", true);
case 35:
_context11.prev = 35;
_context11.t0 = _context11["catch"](15);
return _context11.abrupt("return", false);
case 38:
case "end":
return _context11.stop();
}
}, _callee11, null, [[15, 35]]);
}));
return _DownloadFileFromURL.apply(this, arguments);
}
;
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 DownloadPDFFromComponent(_x2) {
return _DownloadPDFFromComponent.apply(this, arguments);
}
function _DownloadPDFFromComponent() {
_DownloadPDFFromComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(_ref4) {
var frontRef, _ref4$backRef, backRef, _ref4$fileName, fileName, _ref4$orientation, orientation, _ref4$format, format, _ref4$scale, scale, _ref4$canvasOptions, canvasOptions, _ref4$pdfOptions, pdfOptions, getCenteredImageDimensions, frontCanvas, pdf, pdfWidth, pdfHeight, frontDims, frontImg, backCanvas, backDims, backImg;
return _regeneratorRuntime.wrap(function _callee12$(_context12) {
while (1) switch (_context12.prev = _context12.next) {
case 0:
frontRef = _ref4.frontRef, _ref4$backRef = _ref4.backRef, backRef = _ref4$backRef === void 0 ? null : _ref4$backRef, _ref4$fileName = _ref4.fileName, fileName = _ref4$fileName === void 0 ? "document" : _ref4$fileName, _ref4$orientation = _ref4.orientation, orientation = _ref4$orientation === void 0 ? "p" : _ref4$orientation, _ref4$format = _ref4.format, format = _ref4$format === void 0 ? "a4" : _ref4$format, _ref4$scale = _ref4.scale, scale = _ref4$scale === void 0 ? 1 : _ref4$scale, _ref4$canvasOptions = _ref4.canvasOptions, canvasOptions = _ref4$canvasOptions === void 0 ? {} : _ref4$canvasOptions, _ref4$pdfOptions = _ref4.pdfOptions, pdfOptions = _ref4$pdfOptions === void 0 ? {} : _ref4$pdfOptions;
_context12.prev = 1;
getCenteredImageDimensions = function getCenteredImageDimensions(canvas, pdfWidth, pdfHeight) {
var imgWidth = pdfWidth;
var imgHeight = canvas.height * imgWidth / canvas.width;
if (imgHeight > pdfHeight) {
imgHeight = pdfHeight;
imgWidth = canvas.width * imgHeight / canvas.height;
}
var x = (pdfWidth - imgWidth) / 2;
var y = (pdfHeight - imgHeight) / 2;
return {
imgWidth: imgWidth,
imgHeight: imgHeight,
x: x,
y: y
};
};
_context12.next = 5;
return html2canvas(frontRef, _objectSpread({
scale: scale
}, canvasOptions || {}));
case 5:
frontCanvas = _context12.sent;
pdf = new jsPDF(_objectSpread({
orientation: orientation,
unit: "mm",
format: format
}, pdfOptions || {}));
pdfWidth = pdf.internal.pageSize.getWidth();
pdfHeight = pdf.internal.pageSize.getHeight();
frontDims = getCenteredImageDimensions(frontCanvas, pdfWidth, pdfHeight);
frontImg = frontCanvas.toDataURL("image/png");
pdf.addImage(frontImg, "PNG", frontDims.x, frontDims.y, frontDims.imgWidth, frontDims.imgHeight);
if (!backRef) {
_context12.next = 20;
break;
}
_context12.next = 15;
return html2canvas(backRef, {
scale: scale
});
case 15:
backCanvas = _context12.sent;
backDims = getCenteredImageDimensions(backCanvas, pdfWidth, pdfHeight);
backImg = backCanvas.toDataURL("image/png");
pdf.addPage({
format: format,
orientation: orientation
});
pdf.addImage(backImg, "PNG", backDims.x, backDims.y, backDims.imgWidth, backDims.imgHeight);
case 20:
pdf.save("".concat(fileName, ".pdf"));
return _context12.abrupt("return", true);
case 24:
_context12.prev = 24;
_context12.t0 = _context12["catch"](1);
return _context12.abrupt("return", false);
case 27:
case "end":
return _context12.stop();
}
}, _callee12, null, [[1, 24]]);
}));
return _DownloadPDFFromComponent.apply(this, arguments);
}
;
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';
var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
try {
html2canvas(firstPageContent).then(function (firstCanvas) {
var imgData = firstCanvas.toDataURL("image/png");
var pdf = new jsPDF(_objectSpread({
orientation: orientation === "1" ? "l" : "p",
format: "a4",
unit: "mm"
}, options || {}));
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) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
try {
html2canvas(contentRef.current).then(function (canvas) {
var imgData = canvas.toDataURL("image/png");
var pdf = new jsPDF(_objectSpread({
orientation: "p",
format: "a4",
unit: "mm"
}, options || {}));
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 _i3 = 0, _currentKeys = currentKeys; _i3 < _currentKeys.length; _i3++) {
var key = _currentKeys[_i3];
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(pa