UNPKG

@trap_stevo/legendarybuilderproreact-ui

Version:

The legendary UI & utility API that makes your application a legendary application. ~ Created by Steven Compton

1,366 lines (1,363 loc) 136 kB
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"; import { GetDataAtSegment, SetDataAtSegment, DeleteDataAtPath, ParsePath } from "./HUDUniversalUtilitiesManager.js"; 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 ConvertNumberToDisplay(value) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (value === 0) { return "0"; } if (!Number.isFinite(value)) { return String(value); } var _options$maxDecimals = options.maxDecimals, maxDecimals = _options$maxDecimals === void 0 ? 1 : _options$maxDecimals, _options$minDecimals = options.minDecimals, minDecimals = _options$minDecimals === void 0 ? 0 : _options$minDecimals, _options$rounding = options.rounding, rounding = _options$rounding === void 0 ? "round" : _options$rounding, _options$unitSpace = options.unitSpace, unitSpace = _options$unitSpace === void 0 ? false : _options$unitSpace, _options$unitStyle = options.unitStyle, unitStyle = _options$unitStyle === void 0 ? "financial" : _options$unitStyle, units = options.units, _options$base = options.base, base = _options$base === void 0 ? 1000 : _options$base, _options$useGrouping = options.useGrouping, useGrouping = _options$useGrouping === void 0 ? true : _options$useGrouping, locale = options.locale, _options$abbreviateTh = options.abbreviateThreshold, abbreviateThreshold = _options$abbreviateTh === void 0 ? 1000 : _options$abbreviateTh, _options$forceSign = options.forceSign, forceSign = _options$forceSign === void 0 ? false : _options$forceSign, _options$stripInsigni = options.stripInsignificantZeros, stripInsignificantZeros = _options$stripInsigni === void 0 ? true : _options$stripInsigni, maxUnitIndex = options.maxUnitIndex, currencySymbol = options.currencySymbol, _options$currencyPosi = options.currencyPosition, currencyPosition = _options$currencyPosi === void 0 ? "prefix" : _options$currencyPosi, _options$accountingNe = options.accountingNegatives, accountingNegatives = _options$accountingNe === void 0 ? false : _options$accountingNe, _options$longCase = options.longCase, longCase = _options$longCase === void 0 ? "title" : _options$longCase; var unitsLongTitle = ["", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion"]; var unitsFinancial = ["", "K", "M", "B", "T", "P", "E", "Z", "Y", "R", "Q"]; var unitsSI = ["", "k", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"]; var unitsLongLower = unitsLongTitle.map(function (u) { return u.toLowerCase(); }); var presetForStyle = unitStyle === "si" ? unitsSI : unitStyle === "long" ? longCase === "lower" ? unitsLongLower : unitsLongTitle : unitsFinancial; var unitList = Array.isArray(units) && units.length ? units : presetForStyle; var abs = Math.abs(value); var numberFmt = new Intl.NumberFormat(locale, { minimumFractionDigits: Math.min(minDecimals, maxDecimals), maximumFractionDigits: maxDecimals, useGrouping: useGrouping }); var roundWith = function roundWith(num, decimals) { var f = Math.pow(10, decimals); switch (rounding) { case "floor": return Math.floor(num * f) / f; case "ceil": return Math.ceil(num * f) / f; case "truncate": return (num < 0 ? Math.ceil(num * f) : Math.floor(num * f)) / f; default: return Math.round(num * f) / f; } }; var output; if (abs < abbreviateThreshold) { output = numberFmt.format(value); if (stripInsignificantZeros && maxDecimals > 0) { output = value.toLocaleString(locale, { minimumFractionDigits: minDecimals, maximumFractionDigits: maxDecimals, useGrouping: useGrouping }); } if (forceSign && value > 0) { output = "+".concat(output); } } else { var rawIndex = Math.floor(Math.log(abs) / Math.log(base)); var cappedMax = maxUnitIndex != null ? Math.min(maxUnitIndex, unitList.length - 1) : unitList.length - 1; var i = Math.min(rawIndex, cappedMax); var scaled = value / Math.pow(base, i); var rounded = roundWith(scaled, maxDecimals); var mantissa = rounded.toLocaleString(locale, { minimumFractionDigits: minDecimals, maximumFractionDigits: maxDecimals, useGrouping: useGrouping }); if (stripInsignificantZeros && maxDecimals > 0) { mantissa = rounded.toLocaleString(locale, { minimumFractionDigits: minDecimals, maximumFractionDigits: maxDecimals, useGrouping: useGrouping }); } if (forceSign && value > 0) { mantissa = "+".concat(mantissa); } var unit = unitList[i] || ""; var joiner = unit ? unitSpace ? " " : "" : ""; output = unitStyle === "long" && unit ? "".concat(mantissa).concat(joiner).concat(unit) : "".concat(mantissa).concat(joiner).concat(unit); } if (currencySymbol) { if (accountingNegatives && value < 0) { var stripped = output.replace(/^-\s?/, ""); return "(".concat(currencyPosition === "prefix" ? currencySymbol + stripped : stripped + currencySymbol, ")"); } if (currencyPosition === "suffix") { return "".concat(output).concat(currencySymbol); } else { if (output.startsWith("-")) { return "-".concat(currencySymbol).concat(output.slice(1)); } if (output.startsWith("+")) { return "+".concat(currencySymbol).concat(output.slice(1)); } return "".concat(currencySymbol).concat(output); } } return output; } ; 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; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (bytes === 0) { return "0 Bytes"; } if (!Number.isFinite(bytes)) { return String(bytes); } var _options$unitSystem = options.unitSystem, unitSystem = _options$unitSystem === void 0 ? "legacy" : _options$unitSystem, _options$unitSpace2 = options.unitSpace, unitSpace = _options$unitSpace2 === void 0 ? true : _options$unitSpace2, maxUnitIndex = options.maxUnitIndex; var unitsSI = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "RB", "QB"]; var unitsIEC = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; var unitsLegacy = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; var si = unitSystem === "si"; var base = si ? 1000 : 1024; var units = unitSystem === "legacy" ? unitsLegacy : si ? unitsSI : unitsIEC; var abs = Math.abs(bytes); var i = Math.floor(Math.log(abs) / Math.log(base)); var iMax = maxUnitIndex != null ? Math.min(maxUnitIndex, units.length - 1) : units.length - 1; if (i > iMax) { i = iMax; } var value = bytes / Math.pow(base, i); var num = parseFloat(value.toFixed(decimalPoints)).toLocaleString(undefined, { maximumFractionDigits: decimalPoints, minimumFractionDigits: 0 }); var unit = units[i] || ""; if (unitSystem === "legacy" && i === 0) { unit = Math.abs(bytes) === 1 ? "Byte" : "Bytes"; } var join = unit ? unitSpace ? " " : "" : ""; return num + join + unit; } ; 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 ConvertToPhoneNumber(value) { var digits = value.replace(/\D/g, ""); if (digits.length <= 3) { return digits; } else if (digits.length <= 6) { return "(".concat(digits.slice(0, 3), ") ").concat(digits.slice(3)); } return "(".concat(digits.slice(0, 3), ") ").concat(digits.slice(3, 6), "-").concat(digits.slice(6, 10)); } ; 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 SeparateText(input, options) { options = options || {}; var dedupe = options.dedupe !== false; var sort = options.sort === true; var normalize = options.normalize === "none" ? "none" : "upper"; var splitRegex = options.splitRegex instanceof RegExp ? options.pattern : /[,\s]+/g; var transform = typeof options.transform === "function" ? options.transform : null; var validate = options.validate; var rawParts = String(input).split(splitRegex).map(function (s) { return s.trim(); }).filter(function (s) { return s.length > 0; }); var seen = new Set(); var invalid = []; var values = []; var _iterator3 = _createForOfIteratorHelper(rawParts), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var part = _step3.value; if (transform) { part = transform(part); } var ok = true; if (validate instanceof RegExp) { ok = validate.test(part); } else if (typeof validate === "function") { ok = !!validate(part); } if (!ok) { invalid.push(part); continue; } if (dedupe) { if (!seen.has(part)) { seen.add(part); values.push(part); } } else { values.push(part); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } if (sort) { values.sort(function (a, b) { return a.localeCompare(b, "en"); }); } return { stats: { total: rawParts.length, valid: values.length, invalid: invalid.length, unique: dedupe ? values.length : new Set(values).size }, invalid: invalid, values: values }; } ; 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 ConvertDateToTime(dateString) { var includeLeadingZeroHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var includeSeconds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var includeTimeZone = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var date = new Date(dateString); var timeOptions = { hour: includeLeadingZeroHour ? "2-digit" : "numeric", minute: "2-digit", hour12: true }; if (includeSeconds) { timeOptions.second = "2-digit"; } var formattedTime = date.toLocaleTimeString("en-US", timeOptions); if (includeTimeZone) { var timeZone = date.toTimeString().match(/\(([^)]+)\)/)[1]; formattedTime += " (".concat(timeZone, ")"); } return formattedTime; } ; 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 _iterator4 = _createForOfIteratorHelper(thresholdArray), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var t = _step4.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) { _iterator4.e(err); } finally { _iterator4.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 monthYearMode = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : "exact"; var previous = new Date(previousDate); var current = new Date(currentDate); if (Number.isNaN(previous.getTime()) || Number.isNaN(current.getTime())) { return null; } 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 normalizeUnit = function normalizeUnit(u) { var s = String(u || "").toLowerCase(); var map = { millisecond: "milliseconds", milliseconds: "milliseconds", ms: "milliseconds", second: "seconds", seconds: "seconds", sec: "seconds", secs: "seconds", s: "seconds", minute: "minutes", minutes: "minutes", min: "minutes", mins: "minutes", hour: "hours", hours: "hours", hr: "hours", hrs: "hours", day: "days", days: "days", week: "weeks", weeks: "weeks", wk: "weeks", wks: "weeks", month: "months", months: "months", mo: "months", year: "years", years: "years", yr: "years", yrs: "years", decade: "decades", decades: "decades", dec: "decades", century: "centuries", centuries: "centuries", cent: "centuries", millennium: "millennia", millennia: "millennia", mil: "millennia" }; return map[s] || s; }; var u = normalizeUnit(unit); var diffCalendarMonths = function diffCalendarMonths(a, b) { var sign = b >= a ? 1 : -1; var ay = a.getFullYear(); var am = a.getMonth(); var by = b.getFullYear(); var bm = b.getMonth(); var months = (by - ay) * 12 + (bm - am); var aCopy = new Date(a); aCopy.setMonth(aCopy.getMonth() + months); if (sign > 0 && b < aCopy || sign < 0 && b > aCopy) { months -= sign; aCopy.setMonth(aCopy.getMonth() - sign); } var monthStart = new Date(aCopy); var nextMonth = new Date(aCopy); nextMonth.setMonth(nextMonth.getMonth() + sign); var monthSpanMs = Math.abs(nextMonth - monthStart); var tailMs = Math.abs(b - aCopy); var frac = monthSpanMs ? Math.min(tailMs / monthSpanMs, 1) : 0; return months + sign * frac; }; var diffCalendarYears = function diffCalendarYears(a, b) { return diffCalendarMonths(a, b) / 12; }; var msInSecond = 1000; var msInMinute = msInSecond * 60; var msInHour = msInMinute * 60; var msInDay = msInHour * 24; var msInWeek = msInDay * 7; var daysPerYear = 365.2425; var daysPerMonth = daysPerYear / 12; var conversions = { milliseconds: 1, seconds: msInSecond, minutes: msInMinute, hours: msInHour, days: msInDay, weeks: msInWeek, months: msInDay * daysPerMonth, years: msInDay * daysPerYear, decades: msInDay * daysPerYear * 10, centuries: msInDay * daysPerYear * 100, millennia: msInDay * daysPerYear * 1000 }; var diffInMilliseconds = current - previous; var value; if (u === "months" || u === "years" || u === "decades" || u === "centuries" || u === "millennia") { if (monthYearMode === "calendar") { if (u === "months") { value = diffCalendarMonths(previous, current); } else if (u === "years") { value = diffCalendarYears(previous, current); } else if (u === "decades") { value = diffCalendarYears(previous, current) / 10; } else if (u === "centuries") { value = diffCalendarYears(previous, current) / 100; } else { value = diffCalendarYears(previous, current) / 1000; } } else { value = diffInMilliseconds / conversions[u]; } } else { if (!conversions[u]) { throw new Error('Unsupported unit "' + unit + '". Supported units include milliseconds, seconds, minutes, hours, days, weeks, months, years, decades, centuries, millennia.'); } value = diffInMillisecon