@w3ux/utils 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/base.cjs ADDED
@@ -0,0 +1,176 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/base.ts
30
+ var base_exports = {};
31
+ __export(base_exports, {
32
+ appendOr: () => appendOr,
33
+ appendOrEmpty: () => appendOrEmpty,
34
+ camelize: () => camelize,
35
+ ellipsisFn: () => ellipsisFn,
36
+ formatAccountSs58: () => formatAccountSs58,
37
+ greaterThanZero: () => greaterThanZero,
38
+ isNotZero: () => isNotZero,
39
+ minDecimalPlaces: () => minDecimalPlaces,
40
+ pageFromUri: () => pageFromUri,
41
+ removeHexPrefix: () => removeHexPrefix,
42
+ rmCommas: () => rmCommas,
43
+ shuffle: () => shuffle,
44
+ withTimeout: () => withTimeout
45
+ });
46
+ module.exports = __toCommonJS(base_exports);
47
+ var import_bignumber = require("bignumber.js");
48
+ var import_keyring = __toESM(require("@polkadot/keyring"), 1);
49
+ var camelize = (str) => {
50
+ const convertToString = (string) => {
51
+ if (string) {
52
+ if (typeof string === "string") {
53
+ return string;
54
+ }
55
+ return String(string);
56
+ }
57
+ return "";
58
+ };
59
+ const toWords = (inp) => convertToString(inp).match(
60
+ /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g
61
+ );
62
+ const simpleCamelCase = (inp) => {
63
+ let result = "";
64
+ for (let i = 0; i < inp?.length; i++) {
65
+ const currString = inp[i];
66
+ let tmpStr = currString.toLowerCase();
67
+ if (i != 0) {
68
+ tmpStr = tmpStr.slice(0, 1).toUpperCase() + tmpStr.slice(1, tmpStr.length);
69
+ }
70
+ result += tmpStr;
71
+ }
72
+ return result;
73
+ };
74
+ const w = toWords(str)?.map((a) => a.toLowerCase());
75
+ return simpleCamelCase(w);
76
+ };
77
+ var ellipsisFn = (str, amount = 6, position = "center") => {
78
+ const half = str.length / 2;
79
+ if (amount <= 4) {
80
+ if (position === "center") {
81
+ return str.slice(0, 4) + "..." + str.slice(-4);
82
+ }
83
+ if (position === "end") {
84
+ return str.slice(0, 4) + "...";
85
+ }
86
+ return "..." + str.slice(-4);
87
+ }
88
+ if (position === "center") {
89
+ return amount >= (str.length - 2) / 2 ? str.slice(0, half - 3) + "..." + str.slice(-(half - 3)) : str.slice(0, amount) + "..." + str.slice(-amount);
90
+ }
91
+ if (amount >= str.length) {
92
+ if (position === "end") {
93
+ return str.slice(0, str.length - 3) + "...";
94
+ }
95
+ return "..." + str.slice(-(str.length - 3));
96
+ } else {
97
+ if (position === "end") {
98
+ return str.slice(0, amount) + "...";
99
+ }
100
+ return "..." + str.slice(amount);
101
+ }
102
+ };
103
+ var greaterThanZero = (val) => val.isGreaterThan(0);
104
+ var isNotZero = (val) => !val.isZero();
105
+ var minDecimalPlaces = (val, minDecimals) => {
106
+ const whole = new import_bignumber.BigNumber(rmCommas(val).split(".")[0] || 0);
107
+ const decimals = val.split(".")[1] || "";
108
+ const missingDecimals = new import_bignumber.BigNumber(minDecimals).minus(decimals.length);
109
+ return missingDecimals.isGreaterThan(0) ? `${whole.toFormat(0)}.${decimals.toString()}${"0".repeat(
110
+ missingDecimals.toNumber()
111
+ )}` : val;
112
+ };
113
+ var pageFromUri = (pathname, fallback) => {
114
+ const lastUriItem = pathname.substring(pathname.lastIndexOf("/") + 1);
115
+ const page = lastUriItem.trim() === "" ? fallback : lastUriItem;
116
+ return page.trim();
117
+ };
118
+ var rmCommas = (val) => val.replace(/,/g, "");
119
+ var shuffle = (array) => {
120
+ let currentIndex = array.length;
121
+ let randomIndex;
122
+ while (currentIndex !== 0) {
123
+ randomIndex = Math.floor(Math.random() * currentIndex);
124
+ currentIndex--;
125
+ [array[currentIndex], array[randomIndex]] = [
126
+ array[randomIndex],
127
+ array[currentIndex]
128
+ ];
129
+ }
130
+ return array;
131
+ };
132
+ var withTimeout = (ms, promise, options) => {
133
+ const timeout = new Promise(
134
+ (resolve) => setTimeout(async () => {
135
+ if (typeof options?.onTimeout === "function") {
136
+ options.onTimeout();
137
+ }
138
+ resolve(void 0);
139
+ }, ms)
140
+ );
141
+ return Promise.race([promise, timeout]);
142
+ };
143
+ var appendOrEmpty = (condition, value) => condition ? ` ${value}` : "";
144
+ var appendOr = (condition, value, fallback) => condition ? ` ${value}` : ` ${fallback}`;
145
+ var formatAccountSs58 = (address, ss58) => {
146
+ try {
147
+ const keyring = new import_keyring.default();
148
+ keyring.setSS58Format(ss58);
149
+ const formatted = keyring.addFromAddress(address).address;
150
+ if (formatted !== address) {
151
+ return formatted;
152
+ }
153
+ return null;
154
+ } catch (e) {
155
+ return null;
156
+ }
157
+ };
158
+ var removeHexPrefix = (str) => str.replace(/^0x/, "");
159
+ // Annotate the CommonJS export names for ESM import in node:
160
+ 0 && (module.exports = {
161
+ appendOr,
162
+ appendOrEmpty,
163
+ camelize,
164
+ ellipsisFn,
165
+ formatAccountSs58,
166
+ greaterThanZero,
167
+ isNotZero,
168
+ minDecimalPlaces,
169
+ pageFromUri,
170
+ removeHexPrefix,
171
+ rmCommas,
172
+ shuffle,
173
+ withTimeout
174
+ });
175
+ /* @license Copyright 2024 w3ux authors & contributors
176
+ SPDX-License-Identifier: GPL-3.0-only */
package/base.d.cts ADDED
@@ -0,0 +1,77 @@
1
+ import { BigNumber } from 'bignumber.js';
2
+ import { AnyFunction } from '@w3ux/types';
3
+
4
+ /**
5
+ * @name camelize
6
+ * @summary Converts a string of text to camelCase.
7
+ */
8
+ declare const camelize: (str: string) => string;
9
+ /**
10
+ * @name ellipsisFn
11
+ * @summary Receives an address and creates ellipsis on the given string, based on parameters.
12
+ * @param str - The string to apply the ellipsis on
13
+ * @param amount - The amount of characters that the ellipsis will be
14
+ * @param position - where the ellipsis will apply; if center the amount of character is the
15
+ * same for beginning and end; if "start" or "end" then its only once the amount; defaults to "start"
16
+ */
17
+ declare const ellipsisFn: (str: string, amount?: number, position?: "start" | "end" | "center") => string;
18
+ /**
19
+ * @name greaterThanZero
20
+ * @summary Returns whether a BigNumber is greater than zero.
21
+ */
22
+ declare const greaterThanZero: (val: BigNumber) => boolean;
23
+ /**
24
+ * @name isNotZero
25
+ * @summary Returns whether a BigNumber is zero.
26
+ */
27
+ declare const isNotZero: (val: BigNumber) => boolean;
28
+ /**
29
+ * @name minDecimalPlaces
30
+ * @summary Forces a number to have at least the provided decimal places.
31
+ */
32
+ declare const minDecimalPlaces: (val: string, minDecimals: number) => string;
33
+ /**
34
+ * @name pageFromUri
35
+ * @summary Use url variables to load the default components upon the first page visit.
36
+ */
37
+ declare const pageFromUri: (pathname: string, fallback: string) => string;
38
+ /**
39
+ * @name rmCommas
40
+ * @summary Removes the commas from a string.
41
+ */
42
+ declare const rmCommas: (val: string) => string;
43
+ /**
44
+ * @name shuffle
45
+ * @summary Shuffle a set of objects.
46
+ */
47
+ declare const shuffle: <T>(array: T[]) => T[];
48
+ /**
49
+ * @name withTimeout
50
+ * @summary Timeout a promise after a specified number of milliseconds.
51
+ */
52
+ declare const withTimeout: (ms: number, promise: AnyFunction, options?: {
53
+ onTimeout?: AnyFunction;
54
+ }) => Promise<any>;
55
+ /**
56
+ * @name appendOrEmpty
57
+ * @summary Returns ` value` if a condition is truthy, or an empty string otherwise.
58
+ */
59
+ declare const appendOrEmpty: (condition: boolean | string | undefined, value: string) => string;
60
+ /**
61
+ * @name appendOr
62
+ * @summary Returns ` value` if condition is truthy, or ` fallback` otherwise.
63
+ */
64
+ declare const appendOr: (condition: boolean | string | undefined, value: string, fallback: string) => string;
65
+ /**
66
+ * @name appendOr
67
+ * @summary Formats an address with the supplied ss58 prefix, or returns null if invalid.
68
+ */
69
+ declare const formatAccountSs58: (address: string, ss58: number) => string;
70
+ /**
71
+ * @name removeHexPrefix
72
+ * @summary Takes a string str as input and returns a new string with the "0x" prefix removed if it
73
+ * exists at the beginning of the input string.
74
+ */
75
+ declare const removeHexPrefix: (str: string) => string;
76
+
77
+ export { appendOr, appendOrEmpty, camelize, ellipsisFn, formatAccountSs58, greaterThanZero, isNotZero, minDecimalPlaces, pageFromUri, removeHexPrefix, rmCommas, shuffle, withTimeout };
package/index.cjs ADDED
@@ -0,0 +1,493 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/index.ts
30
+ var src_exports = {};
31
+ __export(src_exports, {
32
+ addedTo: () => addedTo,
33
+ appendOr: () => appendOr,
34
+ appendOrEmpty: () => appendOrEmpty,
35
+ applyWidthAsPadding: () => applyWidthAsPadding,
36
+ camelize: () => camelize,
37
+ capitalizeFirstLetter: () => capitalizeFirstLetter,
38
+ determinePoolDisplay: () => determinePoolDisplay,
39
+ ellipsisFn: () => ellipsisFn,
40
+ evalUnits: () => evalUnits,
41
+ extractUrlValue: () => extractUrlValue,
42
+ formatAccountSs58: () => formatAccountSs58,
43
+ greaterThanZero: () => greaterThanZero,
44
+ inChrome: () => inChrome,
45
+ isNotZero: () => isNotZero,
46
+ isValidAddress: () => isValidAddress,
47
+ isValidHttpUrl: () => isValidHttpUrl,
48
+ localStorageOrDefault: () => localStorageOrDefault,
49
+ makeCancelable: () => makeCancelable,
50
+ matchedProperties: () => matchedProperties,
51
+ mergeDeep: () => mergeDeep,
52
+ minDecimalPlaces: () => minDecimalPlaces,
53
+ pageFromUri: () => pageFromUri,
54
+ planckToUnit: () => planckToUnit,
55
+ remToUnit: () => remToUnit,
56
+ removeHexPrefix: () => removeHexPrefix,
57
+ removeVarFromUrlHash: () => removeVarFromUrlHash,
58
+ removedFrom: () => removedFrom,
59
+ rmCommas: () => rmCommas,
60
+ setStateWithRef: () => setStateWithRef,
61
+ shuffle: () => shuffle,
62
+ snakeToCamel: () => snakeToCamel,
63
+ sortWithNull: () => sortWithNull,
64
+ stringToBigNumber: () => stringToBigNumber,
65
+ transformToBaseUnit: () => transformToBaseUnit,
66
+ unescape: () => unescape,
67
+ unimplemented: () => unimplemented,
68
+ unitToPlanck: () => unitToPlanck,
69
+ varToUrlHash: () => varToUrlHash,
70
+ withTimeout: () => withTimeout
71
+ });
72
+ module.exports = __toCommonJS(src_exports);
73
+
74
+ // src/base.ts
75
+ var import_bignumber = require("bignumber.js");
76
+ var import_keyring = __toESM(require("@polkadot/keyring"), 1);
77
+ var camelize = (str) => {
78
+ const convertToString = (string) => {
79
+ if (string) {
80
+ if (typeof string === "string") {
81
+ return string;
82
+ }
83
+ return String(string);
84
+ }
85
+ return "";
86
+ };
87
+ const toWords = (inp) => convertToString(inp).match(
88
+ /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g
89
+ );
90
+ const simpleCamelCase = (inp) => {
91
+ let result = "";
92
+ for (let i = 0; i < inp?.length; i++) {
93
+ const currString = inp[i];
94
+ let tmpStr = currString.toLowerCase();
95
+ if (i != 0) {
96
+ tmpStr = tmpStr.slice(0, 1).toUpperCase() + tmpStr.slice(1, tmpStr.length);
97
+ }
98
+ result += tmpStr;
99
+ }
100
+ return result;
101
+ };
102
+ const w = toWords(str)?.map((a) => a.toLowerCase());
103
+ return simpleCamelCase(w);
104
+ };
105
+ var ellipsisFn = (str, amount = 6, position = "center") => {
106
+ const half = str.length / 2;
107
+ if (amount <= 4) {
108
+ if (position === "center") {
109
+ return str.slice(0, 4) + "..." + str.slice(-4);
110
+ }
111
+ if (position === "end") {
112
+ return str.slice(0, 4) + "...";
113
+ }
114
+ return "..." + str.slice(-4);
115
+ }
116
+ if (position === "center") {
117
+ return amount >= (str.length - 2) / 2 ? str.slice(0, half - 3) + "..." + str.slice(-(half - 3)) : str.slice(0, amount) + "..." + str.slice(-amount);
118
+ }
119
+ if (amount >= str.length) {
120
+ if (position === "end") {
121
+ return str.slice(0, str.length - 3) + "...";
122
+ }
123
+ return "..." + str.slice(-(str.length - 3));
124
+ } else {
125
+ if (position === "end") {
126
+ return str.slice(0, amount) + "...";
127
+ }
128
+ return "..." + str.slice(amount);
129
+ }
130
+ };
131
+ var greaterThanZero = (val) => val.isGreaterThan(0);
132
+ var isNotZero = (val) => !val.isZero();
133
+ var minDecimalPlaces = (val, minDecimals) => {
134
+ const whole = new import_bignumber.BigNumber(rmCommas(val).split(".")[0] || 0);
135
+ const decimals = val.split(".")[1] || "";
136
+ const missingDecimals = new import_bignumber.BigNumber(minDecimals).minus(decimals.length);
137
+ return missingDecimals.isGreaterThan(0) ? `${whole.toFormat(0)}.${decimals.toString()}${"0".repeat(
138
+ missingDecimals.toNumber()
139
+ )}` : val;
140
+ };
141
+ var pageFromUri = (pathname, fallback) => {
142
+ const lastUriItem = pathname.substring(pathname.lastIndexOf("/") + 1);
143
+ const page = lastUriItem.trim() === "" ? fallback : lastUriItem;
144
+ return page.trim();
145
+ };
146
+ var rmCommas = (val) => val.replace(/,/g, "");
147
+ var shuffle = (array) => {
148
+ let currentIndex = array.length;
149
+ let randomIndex;
150
+ while (currentIndex !== 0) {
151
+ randomIndex = Math.floor(Math.random() * currentIndex);
152
+ currentIndex--;
153
+ [array[currentIndex], array[randomIndex]] = [
154
+ array[randomIndex],
155
+ array[currentIndex]
156
+ ];
157
+ }
158
+ return array;
159
+ };
160
+ var withTimeout = (ms, promise, options) => {
161
+ const timeout = new Promise(
162
+ (resolve) => setTimeout(async () => {
163
+ if (typeof options?.onTimeout === "function") {
164
+ options.onTimeout();
165
+ }
166
+ resolve(void 0);
167
+ }, ms)
168
+ );
169
+ return Promise.race([promise, timeout]);
170
+ };
171
+ var appendOrEmpty = (condition, value) => condition ? ` ${value}` : "";
172
+ var appendOr = (condition, value, fallback) => condition ? ` ${value}` : ` ${fallback}`;
173
+ var formatAccountSs58 = (address, ss58) => {
174
+ try {
175
+ const keyring = new import_keyring.default();
176
+ keyring.setSS58Format(ss58);
177
+ const formatted = keyring.addFromAddress(address).address;
178
+ if (formatted !== address) {
179
+ return formatted;
180
+ }
181
+ return null;
182
+ } catch (e) {
183
+ return null;
184
+ }
185
+ };
186
+ var removeHexPrefix = (str) => str.replace(/^0x/, "");
187
+
188
+ // src/unit.ts
189
+ var import_keyring2 = require("@polkadot/keyring");
190
+ var import_util = require("@polkadot/util");
191
+ var import_bignumber2 = require("bignumber.js");
192
+ var remToUnit = (rem) => Number(rem.slice(0, rem.length - 3)) * parseFloat(getComputedStyle(document.documentElement).fontSize);
193
+ var planckToUnit = (val, units) => new import_bignumber2.BigNumber(
194
+ val.dividedBy(new import_bignumber2.BigNumber(10).exponentiatedBy(units)).toFixed(units)
195
+ );
196
+ var unitToPlanck = (val, units) => {
197
+ const init = new import_bignumber2.BigNumber(!val.length || !val ? "0" : val);
198
+ return (!init.isNaN() ? init : new import_bignumber2.BigNumber(0)).multipliedBy(new import_bignumber2.BigNumber(10).exponentiatedBy(units)).integerValue();
199
+ };
200
+ var capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1);
201
+ var snakeToCamel = (str) => str.toLowerCase().replace(
202
+ /([-_][a-z])/g,
203
+ (group) => group.toUpperCase().replace("-", "").replace("_", "")
204
+ );
205
+ var setStateWithRef = (value, setState, ref) => {
206
+ setState(value);
207
+ ref.current = value;
208
+ };
209
+ var localStorageOrDefault = (key, _default, parse = false) => {
210
+ const val = localStorage.getItem(key);
211
+ if (val === null) {
212
+ return _default;
213
+ }
214
+ if (parse) {
215
+ return JSON.parse(val);
216
+ }
217
+ return val;
218
+ };
219
+ var isValidAddress = (address) => {
220
+ try {
221
+ (0, import_keyring2.encodeAddress)((0, import_util.isHex)(address) ? (0, import_util.hexToU8a)(address) : (0, import_keyring2.decodeAddress)(address));
222
+ return true;
223
+ } catch (e) {
224
+ return false;
225
+ }
226
+ };
227
+ var determinePoolDisplay = (address, batchItem) => {
228
+ const defaultDisplay = ellipsisFn(address, 6);
229
+ let display = batchItem ?? defaultDisplay;
230
+ const displayAsBytes = (0, import_util.u8aToString)((0, import_util.u8aUnwrapBytes)(display));
231
+ if (displayAsBytes !== "") {
232
+ display = displayAsBytes;
233
+ }
234
+ if (display === "") {
235
+ display = defaultDisplay;
236
+ }
237
+ return display;
238
+ };
239
+ var extractUrlValue = (key, url) => {
240
+ if (typeof url === "undefined") {
241
+ url = window.location.href;
242
+ }
243
+ const match = url.match(`[?&]${key}=([^&]+)`);
244
+ return match ? match[1] : null;
245
+ };
246
+ var varToUrlHash = (key, val, addIfMissing) => {
247
+ const hash = window.location.hash;
248
+ const [page, params] = hash.split("?");
249
+ const searchParams = new URLSearchParams(params);
250
+ if (searchParams.get(key) === null && !addIfMissing) {
251
+ return;
252
+ }
253
+ searchParams.set(key, val);
254
+ window.location.hash = `${page}?${searchParams.toString()}`;
255
+ };
256
+ var removeVarFromUrlHash = (key) => {
257
+ const hash = window.location.hash;
258
+ const [page, params] = hash.split("?");
259
+ const searchParams = new URLSearchParams(params);
260
+ if (searchParams.get(key) === null) {
261
+ return;
262
+ }
263
+ searchParams.delete(key);
264
+ const paramsAsStr = searchParams.toString();
265
+ window.location.hash = `${page}${paramsAsStr ? `?${paramsAsStr}` : ``}`;
266
+ };
267
+ var sortWithNull = (ascending) => (a, b) => {
268
+ if (a === b) {
269
+ return 0;
270
+ }
271
+ if (a === null) {
272
+ return 1;
273
+ }
274
+ if (b === null) {
275
+ return -1;
276
+ }
277
+ if (ascending) {
278
+ return a < b ? -1 : 1;
279
+ }
280
+ return a < b ? 1 : -1;
281
+ };
282
+ var applyWidthAsPadding = (subjectRef, containerRef) => {
283
+ if (containerRef.current && subjectRef.current) {
284
+ containerRef.current.style.paddingRight = `${subjectRef.current.offsetWidth + remToUnit("1rem")}px`;
285
+ }
286
+ };
287
+ var unescape = (val) => val.replace(/\\"/g, '"');
288
+ var inChrome = () => {
289
+ const isChromium = window?.chrome || null;
290
+ const winNav = window?.navigator || null;
291
+ const isOpera = typeof window?.opr !== "undefined";
292
+ const isIEedge = winNav?.userAgent.indexOf("Edg") > -1 || false;
293
+ const isIOSChrome = winNav?.userAgent.match("CriOS") || false;
294
+ if (isIOSChrome) {
295
+ return true;
296
+ }
297
+ if (isChromium !== null && typeof isChromium !== "undefined" && isOpera === false && isIEedge === false) {
298
+ return true;
299
+ }
300
+ return false;
301
+ };
302
+ var addedTo = (fresh, stale, keys) => typeof fresh !== "object" || typeof stale !== "object" || !keys.length ? [] : fresh.filter(
303
+ (freshItem) => !stale.find(
304
+ (staleItem) => keys.every(
305
+ (key) => !(key in staleItem) || !(key in freshItem) ? false : staleItem[key] === freshItem[key]
306
+ )
307
+ )
308
+ );
309
+ var removedFrom = (fresh, stale, keys) => typeof fresh !== "object" || typeof stale !== "object" || !keys.length ? [] : stale.filter(
310
+ (staleItem) => !fresh.find(
311
+ (freshItem) => keys.every(
312
+ (key) => !(key in staleItem) || !(key in freshItem) ? false : freshItem[key] === staleItem[key]
313
+ )
314
+ )
315
+ );
316
+ var matchedProperties = (objX, objY, keys) => typeof objX !== "object" || typeof objY !== "object" || !keys.length ? [] : objY.filter(
317
+ (x) => objX.find(
318
+ (y) => keys.every(
319
+ (key) => !(key in x) || !(key in y) ? false : y[key] === x[key]
320
+ )
321
+ )
322
+ );
323
+ var isValidHttpUrl = (string) => {
324
+ let url;
325
+ try {
326
+ url = new URL(string);
327
+ } catch (_) {
328
+ return false;
329
+ }
330
+ return url.protocol === "http:" || url.protocol === "https:";
331
+ };
332
+ var makeCancelable = (promise) => {
333
+ let hasCanceled = false;
334
+ const wrappedPromise = new Promise((resolve, reject) => {
335
+ promise.then(
336
+ (val) => hasCanceled ? reject(Error("Cancelled")) : resolve(val)
337
+ );
338
+ promise.catch(
339
+ (error) => hasCanceled ? reject(Error("Cancelled")) : reject(error)
340
+ );
341
+ });
342
+ return {
343
+ promise: wrappedPromise,
344
+ cancel: () => {
345
+ hasCanceled = true;
346
+ }
347
+ };
348
+ };
349
+ var getSiValue = (si2) => new import_bignumber2.BigNumber(10).pow(new import_bignumber2.BigNumber(si2));
350
+ var si = [
351
+ { value: getSiValue(24), symbol: "y", isMil: true },
352
+ { value: getSiValue(21), symbol: "z", isMil: true },
353
+ { value: getSiValue(18), symbol: "a", isMil: true },
354
+ { value: getSiValue(15), symbol: "f", isMil: true },
355
+ { value: getSiValue(12), symbol: "p", isMil: true },
356
+ { value: getSiValue(9), symbol: "n", isMil: true },
357
+ { value: getSiValue(6), symbol: "\u03BC", isMil: true },
358
+ { value: getSiValue(3), symbol: "m", isMil: true },
359
+ { value: new import_bignumber2.BigNumber(1), symbol: "" },
360
+ { value: getSiValue(3), symbol: "k" },
361
+ { value: getSiValue(6), symbol: "M" },
362
+ { value: getSiValue(9), symbol: "G" },
363
+ { value: getSiValue(12), symbol: "T" },
364
+ { value: getSiValue(15), symbol: "P" },
365
+ { value: getSiValue(18), symbol: "E" },
366
+ { value: getSiValue(21), symbol: "Y" },
367
+ { value: getSiValue(24), symbol: "Z" }
368
+ ];
369
+ var allowedSymbols = si.map((s) => s.symbol).join(", ").replace(", ,", ",");
370
+ var floats = new RegExp("^[+]?[0-9]*[.,]{1}[0-9]*$");
371
+ var ints = new RegExp("^[+]?[0-9]+$");
372
+ var alphaFloats = new RegExp(
373
+ "^[+]?[0-9]*[.,]{1}[0-9]*[" + allowedSymbols + "]{1}$"
374
+ );
375
+ var alphaInts = new RegExp("^[+]?[0-9]*[" + allowedSymbols + "]{1}$");
376
+ var evalUnits = (input, chainDecimals) => {
377
+ input = input && input.replace("+", "");
378
+ if (!floats.test(input) && !ints.test(input) && !alphaInts.test(input) && !alphaFloats.test(input)) {
379
+ return [null, "Input is not correct. Use numbers, floats or expression (e.g. 1k, 1.3m)" /* GIBBERISH */];
380
+ }
381
+ const symbol = input.replace(/[0-9.,]/g, "");
382
+ const siVal = si.find((s) => s.symbol === symbol);
383
+ const numberStr = input.replace(symbol, "").replace(",", ".");
384
+ let numeric = new import_bignumber2.BigNumber(0);
385
+ if (!siVal) {
386
+ return [null, "Provided symbol is not correct" /* SYMBOL_ERROR */];
387
+ }
388
+ const decimalsBn = new import_bignumber2.BigNumber(10).pow(new import_bignumber2.BigNumber(chainDecimals));
389
+ const containDecimal = numberStr.includes(".");
390
+ const [decPart, fracPart] = numberStr.split(".");
391
+ const fracDecimals = fracPart?.length || 0;
392
+ const fracExp = new import_bignumber2.BigNumber(10).pow(new import_bignumber2.BigNumber(fracDecimals));
393
+ numeric = containDecimal ? new import_bignumber2.BigNumber(
394
+ new import_bignumber2.BigNumber(decPart).multipliedBy(fracExp).plus(new import_bignumber2.BigNumber(fracPart))
395
+ ) : new import_bignumber2.BigNumber(new import_bignumber2.BigNumber(numberStr));
396
+ numeric = numeric.multipliedBy(decimalsBn);
397
+ if (containDecimal) {
398
+ numeric = siVal.isMil ? numeric.dividedBy(siVal.value).dividedBy(fracExp) : numeric.multipliedBy(siVal.value).dividedBy(fracExp);
399
+ } else {
400
+ numeric = siVal.isMil ? numeric.dividedBy(siVal.value) : numeric.multipliedBy(siVal.value);
401
+ }
402
+ if (numeric.eq(new import_bignumber2.BigNumber(0))) {
403
+ return [null, "You cannot send 0 funds" /* ZERO */];
404
+ }
405
+ return [numeric, "" /* SUCCESS */];
406
+ };
407
+ var transformToBaseUnit = (estFee, chainDecimals) => {
408
+ const t = estFee.length - chainDecimals;
409
+ let s = "";
410
+ if (t < 0) {
411
+ for (let i = 0; i < Math.abs(t) - 1; i++) {
412
+ s += "0";
413
+ }
414
+ s = s + estFee;
415
+ for (let i = 0; i < s.length; i++) {
416
+ if (s.slice(s.length - 1) !== "0") {
417
+ break;
418
+ }
419
+ s = s.substring(0, s.length - 1);
420
+ }
421
+ s = "0." + s;
422
+ } else {
423
+ s = (parseInt(estFee) / 10 ** chainDecimals).toString();
424
+ }
425
+ return parseFloat(s) !== 0 ? s : "0";
426
+ };
427
+ var unimplemented = ({ ...props }) => {
428
+ };
429
+ var mergeDeep = (target, ...sources) => {
430
+ if (!sources.length) {
431
+ return target;
432
+ }
433
+ const isObject = (item) => item && typeof item === "object" && !Array.isArray(item);
434
+ const source = sources.shift();
435
+ if (isObject(target) && isObject(source)) {
436
+ for (const key in source) {
437
+ if (isObject(source[key])) {
438
+ if (!target[key]) {
439
+ Object.assign(target, { [key]: {} });
440
+ }
441
+ mergeDeep(target[key], source[key]);
442
+ } else {
443
+ Object.assign(target, { [key]: source[key] });
444
+ }
445
+ }
446
+ }
447
+ return mergeDeep(target, ...sources);
448
+ };
449
+ var stringToBigNumber = (value) => new import_bignumber2.BigNumber(rmCommas(value));
450
+ // Annotate the CommonJS export names for ESM import in node:
451
+ 0 && (module.exports = {
452
+ addedTo,
453
+ appendOr,
454
+ appendOrEmpty,
455
+ applyWidthAsPadding,
456
+ camelize,
457
+ capitalizeFirstLetter,
458
+ determinePoolDisplay,
459
+ ellipsisFn,
460
+ evalUnits,
461
+ extractUrlValue,
462
+ formatAccountSs58,
463
+ greaterThanZero,
464
+ inChrome,
465
+ isNotZero,
466
+ isValidAddress,
467
+ isValidHttpUrl,
468
+ localStorageOrDefault,
469
+ makeCancelable,
470
+ matchedProperties,
471
+ mergeDeep,
472
+ minDecimalPlaces,
473
+ pageFromUri,
474
+ planckToUnit,
475
+ remToUnit,
476
+ removeHexPrefix,
477
+ removeVarFromUrlHash,
478
+ removedFrom,
479
+ rmCommas,
480
+ setStateWithRef,
481
+ shuffle,
482
+ snakeToCamel,
483
+ sortWithNull,
484
+ stringToBigNumber,
485
+ transformToBaseUnit,
486
+ unescape,
487
+ unimplemented,
488
+ unitToPlanck,
489
+ varToUrlHash,
490
+ withTimeout
491
+ });
492
+ /* @license Copyright 2024 w3ux authors & contributors
493
+ SPDX-License-Identifier: GPL-3.0-only */
package/index.d.cts ADDED
@@ -0,0 +1,6 @@
1
+ export { appendOr, appendOrEmpty, camelize, ellipsisFn, formatAccountSs58, greaterThanZero, isNotZero, minDecimalPlaces, pageFromUri, removeHexPrefix, rmCommas, shuffle, withTimeout } from './base.cjs';
2
+ export { addedTo, applyWidthAsPadding, capitalizeFirstLetter, determinePoolDisplay, evalUnits, extractUrlValue, inChrome, isValidAddress, isValidHttpUrl, localStorageOrDefault, makeCancelable, matchedProperties, mergeDeep, planckToUnit, remToUnit, removeVarFromUrlHash, removedFrom, setStateWithRef, snakeToCamel, sortWithNull, stringToBigNumber, transformToBaseUnit, unescape, unimplemented, unitToPlanck, varToUrlHash } from './unit.cjs';
3
+ import 'bignumber.js';
4
+ import '@w3ux/types';
5
+ import 'react';
6
+ import './types.cjs';
package/package.json CHANGED
@@ -1,11 +1,18 @@
1
1
  {
2
2
  "name": "@w3ux/utils",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "license": "GPL-3.0-only",
5
- "type": "module",
6
5
  "dependencies": {
7
6
  "@polkadot/keyring": "^12.6.2",
8
7
  "@polkadot/util": "^12.6.2",
9
8
  "bignumber.js": "^9.1.1"
9
+ },
10
+ "main": "index.cjs",
11
+ "module": "index.js",
12
+ "exports": {
13
+ ".": {
14
+ "import": "./index.js",
15
+ "require": "./index.cjs"
16
+ }
10
17
  }
11
18
  }
package/types.cjs ADDED
@@ -0,0 +1,38 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/types.ts
20
+ var types_exports = {};
21
+ __export(types_exports, {
22
+ EvalMessages: () => EvalMessages
23
+ });
24
+ module.exports = __toCommonJS(types_exports);
25
+ var EvalMessages = /* @__PURE__ */ ((EvalMessages2) => {
26
+ EvalMessages2["GIBBERISH"] = "Input is not correct. Use numbers, floats or expression (e.g. 1k, 1.3m)";
27
+ EvalMessages2["ZERO"] = "You cannot send 0 funds";
28
+ EvalMessages2["SUCCESS"] = "";
29
+ EvalMessages2["SYMBOL_ERROR"] = "Provided symbol is not correct";
30
+ EvalMessages2["GENERAL_ERROR"] = "Check your input. Something went wrong";
31
+ return EvalMessages2;
32
+ })(EvalMessages || {});
33
+ // Annotate the CommonJS export names for ESM import in node:
34
+ 0 && (module.exports = {
35
+ EvalMessages
36
+ });
37
+ /* @license Copyright 2024 w3ux authors & contributors
38
+ SPDX-License-Identifier: GPL-3.0-only */
package/types.d.cts ADDED
@@ -0,0 +1,10 @@
1
+ type AnyObject = any;
2
+ declare enum EvalMessages {
3
+ GIBBERISH = "Input is not correct. Use numbers, floats or expression (e.g. 1k, 1.3m)",
4
+ ZERO = "You cannot send 0 funds",
5
+ SUCCESS = "",
6
+ SYMBOL_ERROR = "Provided symbol is not correct",
7
+ GENERAL_ERROR = "Check your input. Something went wrong"
8
+ }
9
+
10
+ export { type AnyObject, EvalMessages };
package/unit.cjs ADDED
@@ -0,0 +1,384 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/unit.ts
30
+ var unit_exports = {};
31
+ __export(unit_exports, {
32
+ addedTo: () => addedTo,
33
+ applyWidthAsPadding: () => applyWidthAsPadding,
34
+ capitalizeFirstLetter: () => capitalizeFirstLetter,
35
+ determinePoolDisplay: () => determinePoolDisplay,
36
+ evalUnits: () => evalUnits,
37
+ extractUrlValue: () => extractUrlValue,
38
+ inChrome: () => inChrome,
39
+ isValidAddress: () => isValidAddress,
40
+ isValidHttpUrl: () => isValidHttpUrl,
41
+ localStorageOrDefault: () => localStorageOrDefault,
42
+ makeCancelable: () => makeCancelable,
43
+ matchedProperties: () => matchedProperties,
44
+ mergeDeep: () => mergeDeep,
45
+ planckToUnit: () => planckToUnit,
46
+ remToUnit: () => remToUnit,
47
+ removeVarFromUrlHash: () => removeVarFromUrlHash,
48
+ removedFrom: () => removedFrom,
49
+ setStateWithRef: () => setStateWithRef,
50
+ snakeToCamel: () => snakeToCamel,
51
+ sortWithNull: () => sortWithNull,
52
+ stringToBigNumber: () => stringToBigNumber,
53
+ transformToBaseUnit: () => transformToBaseUnit,
54
+ unescape: () => unescape,
55
+ unimplemented: () => unimplemented,
56
+ unitToPlanck: () => unitToPlanck,
57
+ varToUrlHash: () => varToUrlHash
58
+ });
59
+ module.exports = __toCommonJS(unit_exports);
60
+ var import_keyring2 = require("@polkadot/keyring");
61
+ var import_util = require("@polkadot/util");
62
+ var import_bignumber2 = require("bignumber.js");
63
+
64
+ // src/base.ts
65
+ var import_bignumber = require("bignumber.js");
66
+ var import_keyring = __toESM(require("@polkadot/keyring"), 1);
67
+ var ellipsisFn = (str, amount = 6, position = "center") => {
68
+ const half = str.length / 2;
69
+ if (amount <= 4) {
70
+ if (position === "center") {
71
+ return str.slice(0, 4) + "..." + str.slice(-4);
72
+ }
73
+ if (position === "end") {
74
+ return str.slice(0, 4) + "...";
75
+ }
76
+ return "..." + str.slice(-4);
77
+ }
78
+ if (position === "center") {
79
+ return amount >= (str.length - 2) / 2 ? str.slice(0, half - 3) + "..." + str.slice(-(half - 3)) : str.slice(0, amount) + "..." + str.slice(-amount);
80
+ }
81
+ if (amount >= str.length) {
82
+ if (position === "end") {
83
+ return str.slice(0, str.length - 3) + "...";
84
+ }
85
+ return "..." + str.slice(-(str.length - 3));
86
+ } else {
87
+ if (position === "end") {
88
+ return str.slice(0, amount) + "...";
89
+ }
90
+ return "..." + str.slice(amount);
91
+ }
92
+ };
93
+ var rmCommas = (val) => val.replace(/,/g, "");
94
+
95
+ // src/unit.ts
96
+ var remToUnit = (rem) => Number(rem.slice(0, rem.length - 3)) * parseFloat(getComputedStyle(document.documentElement).fontSize);
97
+ var planckToUnit = (val, units) => new import_bignumber2.BigNumber(
98
+ val.dividedBy(new import_bignumber2.BigNumber(10).exponentiatedBy(units)).toFixed(units)
99
+ );
100
+ var unitToPlanck = (val, units) => {
101
+ const init = new import_bignumber2.BigNumber(!val.length || !val ? "0" : val);
102
+ return (!init.isNaN() ? init : new import_bignumber2.BigNumber(0)).multipliedBy(new import_bignumber2.BigNumber(10).exponentiatedBy(units)).integerValue();
103
+ };
104
+ var capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1);
105
+ var snakeToCamel = (str) => str.toLowerCase().replace(
106
+ /([-_][a-z])/g,
107
+ (group) => group.toUpperCase().replace("-", "").replace("_", "")
108
+ );
109
+ var setStateWithRef = (value, setState, ref) => {
110
+ setState(value);
111
+ ref.current = value;
112
+ };
113
+ var localStorageOrDefault = (key, _default, parse = false) => {
114
+ const val = localStorage.getItem(key);
115
+ if (val === null) {
116
+ return _default;
117
+ }
118
+ if (parse) {
119
+ return JSON.parse(val);
120
+ }
121
+ return val;
122
+ };
123
+ var isValidAddress = (address) => {
124
+ try {
125
+ (0, import_keyring2.encodeAddress)((0, import_util.isHex)(address) ? (0, import_util.hexToU8a)(address) : (0, import_keyring2.decodeAddress)(address));
126
+ return true;
127
+ } catch (e) {
128
+ return false;
129
+ }
130
+ };
131
+ var determinePoolDisplay = (address, batchItem) => {
132
+ const defaultDisplay = ellipsisFn(address, 6);
133
+ let display = batchItem ?? defaultDisplay;
134
+ const displayAsBytes = (0, import_util.u8aToString)((0, import_util.u8aUnwrapBytes)(display));
135
+ if (displayAsBytes !== "") {
136
+ display = displayAsBytes;
137
+ }
138
+ if (display === "") {
139
+ display = defaultDisplay;
140
+ }
141
+ return display;
142
+ };
143
+ var extractUrlValue = (key, url) => {
144
+ if (typeof url === "undefined") {
145
+ url = window.location.href;
146
+ }
147
+ const match = url.match(`[?&]${key}=([^&]+)`);
148
+ return match ? match[1] : null;
149
+ };
150
+ var varToUrlHash = (key, val, addIfMissing) => {
151
+ const hash = window.location.hash;
152
+ const [page, params] = hash.split("?");
153
+ const searchParams = new URLSearchParams(params);
154
+ if (searchParams.get(key) === null && !addIfMissing) {
155
+ return;
156
+ }
157
+ searchParams.set(key, val);
158
+ window.location.hash = `${page}?${searchParams.toString()}`;
159
+ };
160
+ var removeVarFromUrlHash = (key) => {
161
+ const hash = window.location.hash;
162
+ const [page, params] = hash.split("?");
163
+ const searchParams = new URLSearchParams(params);
164
+ if (searchParams.get(key) === null) {
165
+ return;
166
+ }
167
+ searchParams.delete(key);
168
+ const paramsAsStr = searchParams.toString();
169
+ window.location.hash = `${page}${paramsAsStr ? `?${paramsAsStr}` : ``}`;
170
+ };
171
+ var sortWithNull = (ascending) => (a, b) => {
172
+ if (a === b) {
173
+ return 0;
174
+ }
175
+ if (a === null) {
176
+ return 1;
177
+ }
178
+ if (b === null) {
179
+ return -1;
180
+ }
181
+ if (ascending) {
182
+ return a < b ? -1 : 1;
183
+ }
184
+ return a < b ? 1 : -1;
185
+ };
186
+ var applyWidthAsPadding = (subjectRef, containerRef) => {
187
+ if (containerRef.current && subjectRef.current) {
188
+ containerRef.current.style.paddingRight = `${subjectRef.current.offsetWidth + remToUnit("1rem")}px`;
189
+ }
190
+ };
191
+ var unescape = (val) => val.replace(/\\"/g, '"');
192
+ var inChrome = () => {
193
+ const isChromium = window?.chrome || null;
194
+ const winNav = window?.navigator || null;
195
+ const isOpera = typeof window?.opr !== "undefined";
196
+ const isIEedge = winNav?.userAgent.indexOf("Edg") > -1 || false;
197
+ const isIOSChrome = winNav?.userAgent.match("CriOS") || false;
198
+ if (isIOSChrome) {
199
+ return true;
200
+ }
201
+ if (isChromium !== null && typeof isChromium !== "undefined" && isOpera === false && isIEedge === false) {
202
+ return true;
203
+ }
204
+ return false;
205
+ };
206
+ var addedTo = (fresh, stale, keys) => typeof fresh !== "object" || typeof stale !== "object" || !keys.length ? [] : fresh.filter(
207
+ (freshItem) => !stale.find(
208
+ (staleItem) => keys.every(
209
+ (key) => !(key in staleItem) || !(key in freshItem) ? false : staleItem[key] === freshItem[key]
210
+ )
211
+ )
212
+ );
213
+ var removedFrom = (fresh, stale, keys) => typeof fresh !== "object" || typeof stale !== "object" || !keys.length ? [] : stale.filter(
214
+ (staleItem) => !fresh.find(
215
+ (freshItem) => keys.every(
216
+ (key) => !(key in staleItem) || !(key in freshItem) ? false : freshItem[key] === staleItem[key]
217
+ )
218
+ )
219
+ );
220
+ var matchedProperties = (objX, objY, keys) => typeof objX !== "object" || typeof objY !== "object" || !keys.length ? [] : objY.filter(
221
+ (x) => objX.find(
222
+ (y) => keys.every(
223
+ (key) => !(key in x) || !(key in y) ? false : y[key] === x[key]
224
+ )
225
+ )
226
+ );
227
+ var isValidHttpUrl = (string) => {
228
+ let url;
229
+ try {
230
+ url = new URL(string);
231
+ } catch (_) {
232
+ return false;
233
+ }
234
+ return url.protocol === "http:" || url.protocol === "https:";
235
+ };
236
+ var makeCancelable = (promise) => {
237
+ let hasCanceled = false;
238
+ const wrappedPromise = new Promise((resolve, reject) => {
239
+ promise.then(
240
+ (val) => hasCanceled ? reject(Error("Cancelled")) : resolve(val)
241
+ );
242
+ promise.catch(
243
+ (error) => hasCanceled ? reject(Error("Cancelled")) : reject(error)
244
+ );
245
+ });
246
+ return {
247
+ promise: wrappedPromise,
248
+ cancel: () => {
249
+ hasCanceled = true;
250
+ }
251
+ };
252
+ };
253
+ var getSiValue = (si2) => new import_bignumber2.BigNumber(10).pow(new import_bignumber2.BigNumber(si2));
254
+ var si = [
255
+ { value: getSiValue(24), symbol: "y", isMil: true },
256
+ { value: getSiValue(21), symbol: "z", isMil: true },
257
+ { value: getSiValue(18), symbol: "a", isMil: true },
258
+ { value: getSiValue(15), symbol: "f", isMil: true },
259
+ { value: getSiValue(12), symbol: "p", isMil: true },
260
+ { value: getSiValue(9), symbol: "n", isMil: true },
261
+ { value: getSiValue(6), symbol: "\u03BC", isMil: true },
262
+ { value: getSiValue(3), symbol: "m", isMil: true },
263
+ { value: new import_bignumber2.BigNumber(1), symbol: "" },
264
+ { value: getSiValue(3), symbol: "k" },
265
+ { value: getSiValue(6), symbol: "M" },
266
+ { value: getSiValue(9), symbol: "G" },
267
+ { value: getSiValue(12), symbol: "T" },
268
+ { value: getSiValue(15), symbol: "P" },
269
+ { value: getSiValue(18), symbol: "E" },
270
+ { value: getSiValue(21), symbol: "Y" },
271
+ { value: getSiValue(24), symbol: "Z" }
272
+ ];
273
+ var allowedSymbols = si.map((s) => s.symbol).join(", ").replace(", ,", ",");
274
+ var floats = new RegExp("^[+]?[0-9]*[.,]{1}[0-9]*$");
275
+ var ints = new RegExp("^[+]?[0-9]+$");
276
+ var alphaFloats = new RegExp(
277
+ "^[+]?[0-9]*[.,]{1}[0-9]*[" + allowedSymbols + "]{1}$"
278
+ );
279
+ var alphaInts = new RegExp("^[+]?[0-9]*[" + allowedSymbols + "]{1}$");
280
+ var evalUnits = (input, chainDecimals) => {
281
+ input = input && input.replace("+", "");
282
+ if (!floats.test(input) && !ints.test(input) && !alphaInts.test(input) && !alphaFloats.test(input)) {
283
+ return [null, "Input is not correct. Use numbers, floats or expression (e.g. 1k, 1.3m)" /* GIBBERISH */];
284
+ }
285
+ const symbol = input.replace(/[0-9.,]/g, "");
286
+ const siVal = si.find((s) => s.symbol === symbol);
287
+ const numberStr = input.replace(symbol, "").replace(",", ".");
288
+ let numeric = new import_bignumber2.BigNumber(0);
289
+ if (!siVal) {
290
+ return [null, "Provided symbol is not correct" /* SYMBOL_ERROR */];
291
+ }
292
+ const decimalsBn = new import_bignumber2.BigNumber(10).pow(new import_bignumber2.BigNumber(chainDecimals));
293
+ const containDecimal = numberStr.includes(".");
294
+ const [decPart, fracPart] = numberStr.split(".");
295
+ const fracDecimals = fracPart?.length || 0;
296
+ const fracExp = new import_bignumber2.BigNumber(10).pow(new import_bignumber2.BigNumber(fracDecimals));
297
+ numeric = containDecimal ? new import_bignumber2.BigNumber(
298
+ new import_bignumber2.BigNumber(decPart).multipliedBy(fracExp).plus(new import_bignumber2.BigNumber(fracPart))
299
+ ) : new import_bignumber2.BigNumber(new import_bignumber2.BigNumber(numberStr));
300
+ numeric = numeric.multipliedBy(decimalsBn);
301
+ if (containDecimal) {
302
+ numeric = siVal.isMil ? numeric.dividedBy(siVal.value).dividedBy(fracExp) : numeric.multipliedBy(siVal.value).dividedBy(fracExp);
303
+ } else {
304
+ numeric = siVal.isMil ? numeric.dividedBy(siVal.value) : numeric.multipliedBy(siVal.value);
305
+ }
306
+ if (numeric.eq(new import_bignumber2.BigNumber(0))) {
307
+ return [null, "You cannot send 0 funds" /* ZERO */];
308
+ }
309
+ return [numeric, "" /* SUCCESS */];
310
+ };
311
+ var transformToBaseUnit = (estFee, chainDecimals) => {
312
+ const t = estFee.length - chainDecimals;
313
+ let s = "";
314
+ if (t < 0) {
315
+ for (let i = 0; i < Math.abs(t) - 1; i++) {
316
+ s += "0";
317
+ }
318
+ s = s + estFee;
319
+ for (let i = 0; i < s.length; i++) {
320
+ if (s.slice(s.length - 1) !== "0") {
321
+ break;
322
+ }
323
+ s = s.substring(0, s.length - 1);
324
+ }
325
+ s = "0." + s;
326
+ } else {
327
+ s = (parseInt(estFee) / 10 ** chainDecimals).toString();
328
+ }
329
+ return parseFloat(s) !== 0 ? s : "0";
330
+ };
331
+ var unimplemented = ({ ...props }) => {
332
+ };
333
+ var mergeDeep = (target, ...sources) => {
334
+ if (!sources.length) {
335
+ return target;
336
+ }
337
+ const isObject = (item) => item && typeof item === "object" && !Array.isArray(item);
338
+ const source = sources.shift();
339
+ if (isObject(target) && isObject(source)) {
340
+ for (const key in source) {
341
+ if (isObject(source[key])) {
342
+ if (!target[key]) {
343
+ Object.assign(target, { [key]: {} });
344
+ }
345
+ mergeDeep(target[key], source[key]);
346
+ } else {
347
+ Object.assign(target, { [key]: source[key] });
348
+ }
349
+ }
350
+ }
351
+ return mergeDeep(target, ...sources);
352
+ };
353
+ var stringToBigNumber = (value) => new import_bignumber2.BigNumber(rmCommas(value));
354
+ // Annotate the CommonJS export names for ESM import in node:
355
+ 0 && (module.exports = {
356
+ addedTo,
357
+ applyWidthAsPadding,
358
+ capitalizeFirstLetter,
359
+ determinePoolDisplay,
360
+ evalUnits,
361
+ extractUrlValue,
362
+ inChrome,
363
+ isValidAddress,
364
+ isValidHttpUrl,
365
+ localStorageOrDefault,
366
+ makeCancelable,
367
+ matchedProperties,
368
+ mergeDeep,
369
+ planckToUnit,
370
+ remToUnit,
371
+ removeVarFromUrlHash,
372
+ removedFrom,
373
+ setStateWithRef,
374
+ snakeToCamel,
375
+ sortWithNull,
376
+ stringToBigNumber,
377
+ transformToBaseUnit,
378
+ unescape,
379
+ unimplemented,
380
+ unitToPlanck,
381
+ varToUrlHash
382
+ });
383
+ /* @license Copyright 2024 w3ux authors & contributors
384
+ SPDX-License-Identifier: GPL-3.0-only */
package/unit.d.cts ADDED
@@ -0,0 +1,171 @@
1
+ import { BigNumber } from 'bignumber.js';
2
+ import { MutableRefObject, RefObject } from 'react';
3
+ import { AnyObject } from './types.cjs';
4
+ import { AnyJson } from '@w3ux/types';
5
+
6
+ /**
7
+ * @name remToUnit
8
+ * @summary Converts a rem string to a number.
9
+ */
10
+ declare const remToUnit: (rem: string) => number;
11
+ /**
12
+ * @name planckToUnit
13
+ * @summary convert planck to the token unit.
14
+ * @description
15
+ * Converts an on chain balance value in BigNumber planck to a decimal value in token unit. (1 token
16
+ * = 10^units planck).
17
+ */
18
+ declare const planckToUnit: (val: BigNumber, units: number) => BigNumber;
19
+ /**
20
+ * @name unitToPlanck
21
+ * @summary Convert the token unit to planck.
22
+ * @description
23
+ * Converts a balance in token unit to an equivalent value in planck by applying the chain decimals
24
+ * point. (1 token = 10^units planck).
25
+ */
26
+ declare const unitToPlanck: (val: string, units: number) => BigNumber;
27
+ /**
28
+ * @name capitalizeFirstLetter
29
+ * @summary Capitalize the first letter of a string.
30
+ */
31
+ declare const capitalizeFirstLetter: (string: string) => string;
32
+ /**
33
+ * @name snakeToCamel
34
+ * @summary converts a string from snake / kebab-case to camel-case.
35
+ */
36
+ declare const snakeToCamel: (str: string) => string;
37
+ /**
38
+ * @name setStateWithRef
39
+ * @summary Synchronize React state and its reference with the provided value.
40
+ */
41
+ declare const setStateWithRef: <T>(value: T, setState: (_state: T) => void, ref: MutableRefObject<T>) => void;
42
+ /**
43
+ * @name localStorageOrDefault
44
+ * @summary Retrieve the local stroage value with the key, return defult value if it is not
45
+ * found.
46
+ */
47
+ declare const localStorageOrDefault: <T>(key: string, _default: T, parse?: boolean) => T | string;
48
+ /**
49
+ * @name isValidAddress
50
+ * @summary Return whether an address is valid Substrate address.
51
+ */
52
+ declare const isValidAddress: (address: string) => boolean;
53
+ /**
54
+ * @name determinePoolDisplay
55
+ * @summary A pool will be displayed with either its set metadata or its address.
56
+ */
57
+ declare const determinePoolDisplay: (address: string, batchItem: AnyJson) => any;
58
+ /**
59
+ * @name extractUrlValue
60
+ * @summary Extracts a URL value from a URL string.
61
+ */
62
+ declare const extractUrlValue: (key: string, url?: string) => string;
63
+ /**
64
+ * @name varToUrlHash
65
+ * @summary Puts a variable into the URL hash as a param.
66
+ * @description
67
+ * Since url variables are added to the hash and are not treated as URL params, the params are split
68
+ * and parsed into a `URLSearchParams`.
69
+ */
70
+ declare const varToUrlHash: (key: string, val: string, addIfMissing: boolean) => void;
71
+ /**
72
+ * @name removeVarFromUrlHash
73
+ * @summary
74
+ * Removes a variable `key` from the URL hash if it exists. Removes dangling `?` if no URL variables
75
+ * exist.
76
+ */
77
+ declare const removeVarFromUrlHash: (key: string) => void;
78
+ /**
79
+ * @name sortWithNull
80
+ * @summary Sorts an array with nulls last.
81
+ */
82
+ declare const sortWithNull: (ascending: boolean) => (a: AnyJson, b: AnyJson) => 0 | 1 | -1;
83
+ /**
84
+ * @name applyWidthAsPadding
85
+ * @summary Applies width of subject to paddingRight of container.
86
+ */
87
+ declare const applyWidthAsPadding: (subjectRef: RefObject<HTMLDivElement>, containerRef: RefObject<HTMLDivElement>) => void;
88
+ /**
89
+ * @name unescape
90
+ * @summary Replaces \” with “
91
+ */
92
+ declare const unescape: (val: string) => string;
93
+ /**
94
+ * @name inChrome
95
+ * @summary Whether the application is rendering in Chrome.
96
+ */
97
+ declare const inChrome: () => boolean;
98
+ /**
99
+ * @name addedTo
100
+ * @summary Given 2 objects and some keys, return items in the fresh object that do not exist in the
101
+ * stale object by matching the given common key values of both objects.
102
+ */
103
+ declare const addedTo: (fresh: AnyObject[], stale: AnyObject[], keys: string[]) => AnyObject[];
104
+ /**
105
+ * @name removedFrom
106
+ * @summary Given 2 objects and some keys, return items in the stale object that do not exist in the
107
+ * fresh object by matching the given common key values of both objects.
108
+ */
109
+ declare const removedFrom: (fresh: AnyObject[], stale: AnyObject[], keys: string[]) => AnyObject[];
110
+ /**
111
+ * @name matchedProperties
112
+ * @summary Given 2 objects and some keys, return items in object 1 that also exist in object 2 by
113
+ * matching the given common key values of both objects.
114
+ */
115
+ declare const matchedProperties: (objX: AnyObject[], objY: AnyObject[], keys: string[]) => AnyObject[];
116
+ /**
117
+ * @name isValidHttpUrl
118
+ * @summary Give a string, return whether it is a valid http URL.
119
+ * @param string - The string to check.
120
+ */
121
+ declare const isValidHttpUrl: (string: string) => boolean;
122
+ /**
123
+ * @name makeCancelable
124
+ * @summary Makes a promise cancellable.
125
+ * @param promise - The promise to make cancellable.
126
+ */
127
+ declare const makeCancelable: (promise: Promise<AnyObject>) => {
128
+ promise: Promise<unknown>;
129
+ cancel: () => void;
130
+ };
131
+ /**
132
+ * A function that identifes integer/float(comma or dot)/expressions (such as 1k)
133
+ * and converts to actual value (or reports an error).
134
+ * @param {string} input
135
+ * @returns {[number | null, string]} an array of 2 items
136
+ * the first is the actual calculated number (or null if none) while
137
+ * the second is the message that should appear in case of error
138
+ */
139
+ declare const evalUnits: (input: string, chainDecimals: number) => [BigNumber | null, string];
140
+ /**
141
+ * The transformToBaseUnit function is used to transform a given estimated
142
+ * fee value from its current representation to its base unit representation,
143
+ * considering the provided chain decimals. The function is designed to handle
144
+ * cases where the chain decimals are either greater or less than the length
145
+ * of the estimated fee.
146
+ * @param {string} estFee : The estimated fee value that needs to be transformed
147
+ * to its base unit representation.
148
+ * @param {number} chainDecimals: The number of decimal places used by the blockchain.
149
+ */
150
+ declare const transformToBaseUnit: (estFee: string, chainDecimals: number) => string;
151
+ /**
152
+ * @name unimplemented
153
+ * @summary A placeholder function to signal a deliberate unimplementation.
154
+ * Consumes an arbitrary number of props.
155
+ */
156
+ declare const unimplemented: ({ ...props }: {
157
+ [x: string]: any;
158
+ }) => void;
159
+ /**
160
+ * Deep merge two objects.
161
+ * @param target
162
+ * @param ...sources
163
+ */
164
+ declare const mergeDeep: (target: AnyObject, ...sources: AnyObject[]) => AnyObject;
165
+ /**
166
+ * @name stringToBigNumber
167
+ * @summary Converts a balance string into a `BigNumber`.
168
+ */
169
+ declare const stringToBigNumber: (value: string) => BigNumber;
170
+
171
+ export { addedTo, applyWidthAsPadding, capitalizeFirstLetter, determinePoolDisplay, evalUnits, extractUrlValue, inChrome, isValidAddress, isValidHttpUrl, localStorageOrDefault, makeCancelable, matchedProperties, mergeDeep, planckToUnit, remToUnit, removeVarFromUrlHash, removedFrom, setStateWithRef, snakeToCamel, sortWithNull, stringToBigNumber, transformToBaseUnit, unescape, unimplemented, unitToPlanck, varToUrlHash };