@pisell/utils 1.0.28 → 1.0.30

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.
@@ -0,0 +1 @@
1
+ export declare const uniqueByKey: <T>(arr: T[], key: keyof T) => T[];
@@ -0,0 +1,24 @@
1
+ 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; } } }; }
2
+ 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); }
3
+ 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; }
4
+ export var uniqueByKey = function uniqueByKey(arr, key) {
5
+ var seen = new Set();
6
+ var result = [];
7
+ var _iterator = _createForOfIteratorHelper(arr),
8
+ _step;
9
+ try {
10
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
11
+ var item = _step.value;
12
+ var keyValue = item[key];
13
+ if (!seen.has(keyValue)) {
14
+ seen.add(keyValue);
15
+ result.push(item);
16
+ }
17
+ }
18
+ } catch (err) {
19
+ _iterator.e(err);
20
+ } finally {
21
+ _iterator.f();
22
+ }
23
+ return result;
24
+ };
package/es/document.d.ts CHANGED
@@ -6,3 +6,8 @@
6
6
  export declare const setTheme: (themes: {
7
7
  [key: string]: string;
8
8
  }) => void;
9
+ /**
10
+ * 复制到剪切板
11
+ * @param text
12
+ */
13
+ export declare const copyToClipboard: (text: string) => Promise<void>;
package/es/document.js CHANGED
@@ -1,3 +1,7 @@
1
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
2
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
3
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
1
5
  /**
2
6
  * @Title: 设置主题
3
7
  * @Describe: 传入字符串键值对
@@ -13,4 +17,43 @@ export var setTheme = function setTheme(themes) {
13
17
  } catch (err) {
14
18
  console.error(err);
15
19
  }
16
- };
20
+ };
21
+ var httpCopyToClipboard = function httpCopyToClipboard(text) {
22
+ var textArea = document.createElement('textarea');
23
+ textArea.value = text;
24
+ textArea.style.position = 'fixed';
25
+ textArea.style.top = '-10000px';
26
+ textArea.style.left = '-10000px';
27
+ document.body.appendChild(textArea);
28
+ textArea.focus();
29
+ textArea.select();
30
+ document.execCommand('copy');
31
+ document.body.removeChild(textArea);
32
+ };
33
+
34
+ /**
35
+ * 复制到剪切板
36
+ * @param text
37
+ */
38
+ export var copyToClipboard = /*#__PURE__*/function () {
39
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(text) {
40
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
41
+ while (1) switch (_context.prev = _context.next) {
42
+ case 0:
43
+ if (!navigator.clipboard) {
44
+ _context.next = 4;
45
+ break;
46
+ }
47
+ return _context.abrupt("return", navigator.clipboard.writeText(text));
48
+ case 4:
49
+ return _context.abrupt("return", httpCopyToClipboard(text));
50
+ case 5:
51
+ case "end":
52
+ return _context.stop();
53
+ }
54
+ }, _callee);
55
+ }));
56
+ return function copyToClipboard(_x) {
57
+ return _ref.apply(this, arguments);
58
+ };
59
+ }();
package/es/format.d.ts CHANGED
@@ -9,3 +9,20 @@
9
9
  * @Date: 2023-11-06 16:51
10
10
  */
11
11
  export declare const formatAmount: (amount?: number | string, precision?: number, symbol?: string) => string | number;
12
+ export declare type FormatOptions = {
13
+ /** 小数点后位数 默认是小数点后2位 */
14
+ precision?: number;
15
+ /** 显示货币符号 指的是 ¥$ 等货币符号等显隐,默认是展示 */
16
+ showCurrencySymbol?: boolean;
17
+ /** 千分位 指的是长金额的千分位逗号隔开,比如“123, 245, 315” 这种展现形式,默认是关闭 */
18
+ useThousandsSeparator?: boolean;
19
+ /** 整数位隐藏小数 指的是如果价格为整数,后面的".00" 将被省略以节省页面空间 */
20
+ hideDecimalForWholeNumbers?: boolean;
21
+ };
22
+ /**
23
+ * 根据配置格式化金额
24
+ * @param amount
25
+ * @param symbol
26
+ * @param options
27
+ */
28
+ export declare const formatAmountWithOptions: (amount: string | number | undefined, symbol: string | undefined, options: FormatOptions) => string | number;
package/es/format.js CHANGED
@@ -2,7 +2,7 @@ import { isString, isNumber } from "./typeUtils";
2
2
 
3
3
  /**
4
4
  * @title: 格式化金额
5
- * @description:
5
+ * @description:
6
6
  * @param {number} amount 原金额
7
7
  * @param {number} precision 小数位数
8
8
  * @param {string} symbol 货币符号
@@ -42,6 +42,66 @@ export var formatAmount = function formatAmount() {
42
42
  }
43
43
  }
44
44
 
45
+ // 添加负号
46
+ if (roundedAmount < 0) {
47
+ formattedAmount = '-' + formattedAmount;
48
+ }
49
+ return formattedAmount;
50
+ } catch (err) {
51
+ // 计算错误则返回原金额
52
+ console.error(err);
53
+ return amount;
54
+ }
55
+ };
56
+ /**
57
+ * 根据配置格式化金额
58
+ * @param amount
59
+ * @param symbol
60
+ * @param options
61
+ */
62
+ export var formatAmountWithOptions = function formatAmountWithOptions() {
63
+ var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
64
+ var symbol = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
65
+ var options = arguments.length > 2 ? arguments[2] : undefined;
66
+ var _options$precision = options.precision,
67
+ precision = _options$precision === void 0 ? 2 : _options$precision,
68
+ _options$useThousands = options.useThousandsSeparator,
69
+ useThousandsSeparator = _options$useThousands === void 0 ? false : _options$useThousands,
70
+ _options$showCurrency = options.showCurrencySymbol,
71
+ showCurrencySymbol = _options$showCurrency === void 0 ? true : _options$showCurrency,
72
+ _options$hideDecimalF = options.hideDecimalForWholeNumbers,
73
+ hideDecimalForWholeNumbers = _options$hideDecimalF === void 0 ? true : _options$hideDecimalF;
74
+ // 校验格式
75
+ if (!isString(amount) && !isNumber(amount)) {
76
+ console.error('amount is not a number');
77
+ return amount;
78
+ }
79
+ try {
80
+ // 四舍五入
81
+ var roundedAmount = Math.round(amount * Math.pow(10, precision)) / Math.pow(10, precision);
82
+ // 处理负数情况
83
+ var absoluteAmount = Math.abs(roundedAmount);
84
+ // 截取整数
85
+ var integerPart = Math.floor(absoluteAmount);
86
+ // 截取小数部分并补零
87
+ var decimalPart = (absoluteAmount - integerPart).toFixed(precision).substring(2);
88
+
89
+ // 增加千分位分隔符
90
+ var formattedAmount = useThousandsSeparator ? integerPart.toLocaleString() : integerPart.toString();
91
+
92
+ // 拼接货币符号
93
+ formattedAmount = showCurrencySymbol ? symbol + formattedAmount : formattedAmount;
94
+
95
+ // 添加小数点
96
+ if (precision > 0) {
97
+ formattedAmount += '.' + decimalPart;
98
+
99
+ // 如果小数位是 .00的话 抹去
100
+ if (hideDecimalForWholeNumbers && formattedAmount.indexOf('.00') !== -1) {
101
+ formattedAmount = formattedAmount.substring(0, formattedAmount.length - 3);
102
+ }
103
+ }
104
+
45
105
  // 添加负号
46
106
  if (roundedAmount < 0) {
47
107
  formattedAmount = '-' + formattedAmount;
package/es/index.d.ts CHANGED
@@ -10,3 +10,4 @@ export * from './miniRedux';
10
10
  export * from "./jsBridge";
11
11
  export * from "./image";
12
12
  export * from "./locales";
13
+ export * from "./arrayUtils";
package/es/index.js CHANGED
@@ -10,4 +10,5 @@ export * from "./miniRedux";
10
10
  export * from "./jsBridge";
11
11
  export * from "./image";
12
12
  export * from "./locales";
13
+ export * from "./arrayUtils";
13
14
  // export { default as firebase } from './firebase';
package/es/miniRedux.d.ts CHANGED
@@ -11,6 +11,6 @@ export declare const miniRedux: <State extends Record<string, any>, Namespace ex
11
11
  payload: any;
12
12
  }) => void;
13
13
  }>;
14
- Provider: (ComponentUi: any) => (props: any) => any;
14
+ Provider: (ComponentUi: any) => any;
15
15
  };
16
16
  export {};
package/es/miniRedux.js CHANGED
@@ -10,11 +10,11 @@ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o =
10
10
  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; }
11
11
  function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
12
12
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
13
- import React, { createContext, useCallback, useReducer } from "react";
13
+ import React, { createContext, useCallback, useReducer, forwardRef } from 'react';
14
14
  import { jsx as _jsx } from "react/jsx-runtime";
15
15
  export var miniRedux = function miniRedux(_ref2) {
16
16
  var _ref2$namespace = _ref2.namespace,
17
- namespace = _ref2$namespace === void 0 ? "state" : _ref2$namespace,
17
+ namespace = _ref2$namespace === void 0 ? 'state' : _ref2$namespace,
18
18
  state = _ref2.state,
19
19
  _ref2$reducers = _ref2.reducers,
20
20
  reducers = _ref2$reducers === void 0 ? {} : _ref2$reducers,
@@ -22,7 +22,7 @@ export var miniRedux = function miniRedux(_ref2) {
22
22
  effects = _ref2$effects === void 0 ? {} : _ref2$effects;
23
23
  var Context = /*#__PURE__*/createContext({});
24
24
  var Provider = function Provider(ComponentUi) {
25
- var Components = function Components(props) {
25
+ var Components = /*#__PURE__*/forwardRef(function (props, ref) {
26
26
  var _objectSpread2, _ref5;
27
27
  var _useReducer = useReducer(function (state, _ref3) {
28
28
  var type = _ref3.type,
@@ -57,10 +57,10 @@ export var miniRedux = function miniRedux(_ref2) {
57
57
  return /*#__PURE__*/_jsx(Context.Provider, {
58
58
  value: (_ref5 = {}, _defineProperty(_ref5, namespace, providerState), _defineProperty(_ref5, "dispatch", _dispatch), _ref5),
59
59
  children: /*#__PURE__*/_jsx(ComponentUi, _objectSpread(_objectSpread({}, _props), {}, {
60
- ref: _ref
60
+ ref: ref
61
61
  }))
62
62
  });
63
- };
63
+ });
64
64
  return Components;
65
65
  };
66
66
  return {
@@ -27,7 +27,7 @@ export declare const changeArray: <T>(list: T[] | undefined, item: T, key?: stri
27
27
  * @Date: 2023-12-19 16:54
28
28
  */
29
29
  export declare const getItemByArray: <T>(list: T[] | undefined, item: T, key?: string) => boolean;
30
- export declare const createArray: (length: number, returnItem: any) => any;
30
+ export declare const createArray: (length: number, returnItem: any) => unknown[];
31
31
  /**
32
32
  * 根据对象内容生成唯一id
33
33
  * @param obj
package/es/platform.d.ts CHANGED
@@ -2,3 +2,8 @@ export declare const isIpad: () => boolean;
2
2
  export declare const isMobile: () => boolean;
3
3
  export declare const isAndroid: () => boolean;
4
4
  export declare const isIos: () => boolean;
5
+ export declare const checkEnv: () => number;
6
+ export declare const isWx: () => boolean;
7
+ export declare const isIOS: () => boolean;
8
+ export declare const isWxApp: () => boolean;
9
+ export declare const isSafari: () => boolean;
package/es/platform.js CHANGED
@@ -1,3 +1,4 @@
1
+ var isBrowser = typeof window != 'undefined' && window.document;
1
2
  export var isIpad = function isIpad() {
2
3
  var ua = navigator.userAgent;
3
4
  var isSafari = ua.indexOf("Safari") != -1 && ua.indexOf("Version") != -1;
@@ -33,4 +34,60 @@ export var isAndroid = function isAndroid() {
33
34
  // 是否是ios平台
34
35
  export var isIos = function isIos() {
35
36
  return /iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase());
37
+ };
38
+ export var checkEnv = function checkEnv() {
39
+ // 0: 非浏览器环境
40
+ var env = 0;
41
+ var userAgent = window.navigator.userAgent;
42
+ var isOpera = userAgent.indexOf('Opera') > -1 || userAgent.indexOf('OPR') > -1; //判断是否Opera浏览器
43
+ var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1; //判断是否IE7~IE10浏览器
44
+ var isIE11 = userAgent.indexOf('compatible') === -1 && userAgent.indexOf('Trident') > -1; //判断是否IE11浏览器
45
+ var isEdge = userAgent.indexOf('Edge') > -1; //判断是否IE的Edge浏览器
46
+ var isFF = userAgent.indexOf('Firefox') > -1; //判断是否Firefox浏览器
47
+ var isSafari = userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1; //判断是否Safari浏览器
48
+ var isChrome = userAgent.indexOf('Chrome') > -1 && userAgent.indexOf('; Win') > -1 && userAgent.indexOf('Safari') > -1; //判断Chrome浏览器
49
+ //常用浏览器
50
+ if (isOpera || isIE || isIE11 || isEdge || isFF || isSafari || isChrome) {
51
+ env = 0;
52
+ } else {
53
+ env = 1;
54
+ }
55
+ return env;
56
+ };
57
+ export var isWx = function isWx() {
58
+ if (isBrowser) {
59
+ var ua = '';
60
+ if (isBrowser) {
61
+ ua = window.navigator.userAgent.toLowerCase();
62
+ }
63
+ //@ts-ignore
64
+ if (ua.match(/MicroMessenger/i) == 'micromessenger') {
65
+ return true;
66
+ }
67
+ return false;
68
+ }
69
+ return false;
70
+ };
71
+ export var isIOS = function isIOS() {
72
+ if (isBrowser) {
73
+ var u = navigator.userAgent;
74
+ var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
75
+ return isiOS;
76
+ }
77
+ return false;
78
+ };
79
+ export var isWxApp = function isWxApp() {
80
+ if (isBrowser) {
81
+ var u = navigator.userAgent;
82
+ var isWxapp = u.indexOf('miniProgram') !== -1;
83
+ return isWxapp;
84
+ }
85
+ return false;
86
+ };
87
+ export var isSafari = function isSafari() {
88
+ if (isBrowser) {
89
+ var userAgent = window.navigator.userAgent;
90
+ return userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1 && userAgent.indexOf('CriOS') === -1 && userAgent.indexOf('ChannelName/Feishu') === -1;
91
+ }
92
+ return false;
36
93
  };
@@ -0,0 +1 @@
1
+ export declare const uniqueByKey: <T>(arr: T[], key: keyof T) => T[];
@@ -0,0 +1,40 @@
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/arrayUtils.ts
20
+ var arrayUtils_exports = {};
21
+ __export(arrayUtils_exports, {
22
+ uniqueByKey: () => uniqueByKey
23
+ });
24
+ module.exports = __toCommonJS(arrayUtils_exports);
25
+ var uniqueByKey = (arr, key) => {
26
+ const seen = /* @__PURE__ */ new Set();
27
+ const result = [];
28
+ for (const item of arr) {
29
+ const keyValue = item[key];
30
+ if (!seen.has(keyValue)) {
31
+ seen.add(keyValue);
32
+ result.push(item);
33
+ }
34
+ }
35
+ return result;
36
+ };
37
+ // Annotate the CommonJS export names for ESM import in node:
38
+ 0 && (module.exports = {
39
+ uniqueByKey
40
+ });
package/lib/document.d.ts CHANGED
@@ -6,3 +6,8 @@
6
6
  export declare const setTheme: (themes: {
7
7
  [key: string]: string;
8
8
  }) => void;
9
+ /**
10
+ * 复制到剪切板
11
+ * @param text
12
+ */
13
+ export declare const copyToClipboard: (text: string) => Promise<void>;
package/lib/document.js CHANGED
@@ -19,6 +19,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  // src/document.ts
20
20
  var document_exports = {};
21
21
  __export(document_exports, {
22
+ copyToClipboard: () => copyToClipboard,
22
23
  setTheme: () => setTheme
23
24
  });
24
25
  module.exports = __toCommonJS(document_exports);
@@ -32,7 +33,27 @@ var setTheme = (themes) => {
32
33
  console.error(err);
33
34
  }
34
35
  };
36
+ var httpCopyToClipboard = (text) => {
37
+ const textArea = document.createElement("textarea");
38
+ textArea.value = text;
39
+ textArea.style.position = "fixed";
40
+ textArea.style.top = "-10000px";
41
+ textArea.style.left = "-10000px";
42
+ document.body.appendChild(textArea);
43
+ textArea.focus();
44
+ textArea.select();
45
+ document.execCommand("copy");
46
+ document.body.removeChild(textArea);
47
+ };
48
+ var copyToClipboard = async (text) => {
49
+ if (navigator.clipboard) {
50
+ return navigator.clipboard.writeText(text);
51
+ } else {
52
+ return httpCopyToClipboard(text);
53
+ }
54
+ };
35
55
  // Annotate the CommonJS export names for ESM import in node:
36
56
  0 && (module.exports = {
57
+ copyToClipboard,
37
58
  setTheme
38
59
  });
package/lib/format.d.ts CHANGED
@@ -9,3 +9,20 @@
9
9
  * @Date: 2023-11-06 16:51
10
10
  */
11
11
  export declare const formatAmount: (amount?: number | string, precision?: number, symbol?: string) => string | number;
12
+ export declare type FormatOptions = {
13
+ /** 小数点后位数 默认是小数点后2位 */
14
+ precision?: number;
15
+ /** 显示货币符号 指的是 ¥$ 等货币符号等显隐,默认是展示 */
16
+ showCurrencySymbol?: boolean;
17
+ /** 千分位 指的是长金额的千分位逗号隔开,比如“123, 245, 315” 这种展现形式,默认是关闭 */
18
+ useThousandsSeparator?: boolean;
19
+ /** 整数位隐藏小数 指的是如果价格为整数,后面的".00" 将被省略以节省页面空间 */
20
+ hideDecimalForWholeNumbers?: boolean;
21
+ };
22
+ /**
23
+ * 根据配置格式化金额
24
+ * @param amount
25
+ * @param symbol
26
+ * @param options
27
+ */
28
+ export declare const formatAmountWithOptions: (amount: string | number | undefined, symbol: string | undefined, options: FormatOptions) => string | number;
package/lib/format.js CHANGED
@@ -19,7 +19,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  // src/format.ts
20
20
  var format_exports = {};
21
21
  __export(format_exports, {
22
- formatAmount: () => formatAmount
22
+ formatAmount: () => formatAmount,
23
+ formatAmountWithOptions: () => formatAmountWithOptions
23
24
  });
24
25
  module.exports = __toCommonJS(format_exports);
25
26
  var import_typeUtils = require("./typeUtils");
@@ -37,7 +38,46 @@ var formatAmount = (amount = 0, precision = 2, symbol = "") => {
37
38
  if (precision > 0) {
38
39
  formattedAmount += "." + decimalPart;
39
40
  if (formattedAmount.indexOf(".00") !== -1) {
40
- formattedAmount = formattedAmount.substring(0, formattedAmount.length - 3);
41
+ formattedAmount = formattedAmount.substring(
42
+ 0,
43
+ formattedAmount.length - 3
44
+ );
45
+ }
46
+ }
47
+ if (roundedAmount < 0) {
48
+ formattedAmount = "-" + formattedAmount;
49
+ }
50
+ return formattedAmount;
51
+ } catch (err) {
52
+ console.error(err);
53
+ return amount;
54
+ }
55
+ };
56
+ var formatAmountWithOptions = (amount = 0, symbol = "", options) => {
57
+ const {
58
+ precision = 2,
59
+ useThousandsSeparator = false,
60
+ showCurrencySymbol = true,
61
+ hideDecimalForWholeNumbers = true
62
+ } = options;
63
+ if (!(0, import_typeUtils.isString)(amount) && !(0, import_typeUtils.isNumber)(amount)) {
64
+ console.error("amount is not a number");
65
+ return amount;
66
+ }
67
+ try {
68
+ const roundedAmount = Math.round(amount * Math.pow(10, precision)) / Math.pow(10, precision);
69
+ const absoluteAmount = Math.abs(roundedAmount);
70
+ const integerPart = Math.floor(absoluteAmount);
71
+ const decimalPart = (absoluteAmount - integerPart).toFixed(precision).substring(2);
72
+ let formattedAmount = useThousandsSeparator ? integerPart.toLocaleString() : integerPart.toString();
73
+ formattedAmount = showCurrencySymbol ? symbol + formattedAmount : formattedAmount;
74
+ if (precision > 0) {
75
+ formattedAmount += "." + decimalPart;
76
+ if (hideDecimalForWholeNumbers && formattedAmount.indexOf(".00") !== -1) {
77
+ formattedAmount = formattedAmount.substring(
78
+ 0,
79
+ formattedAmount.length - 3
80
+ );
41
81
  }
42
82
  }
43
83
  if (roundedAmount < 0) {
@@ -51,5 +91,6 @@ var formatAmount = (amount = 0, precision = 2, symbol = "") => {
51
91
  };
52
92
  // Annotate the CommonJS export names for ESM import in node:
53
93
  0 && (module.exports = {
54
- formatAmount
94
+ formatAmount,
95
+ formatAmountWithOptions
55
96
  });
package/lib/index.d.ts CHANGED
@@ -10,3 +10,4 @@ export * from './miniRedux';
10
10
  export * from "./jsBridge";
11
11
  export * from "./image";
12
12
  export * from "./locales";
13
+ export * from "./arrayUtils";
package/lib/index.js CHANGED
@@ -28,6 +28,7 @@ __reExport(src_exports, require("./miniRedux"), module.exports);
28
28
  __reExport(src_exports, require("./jsBridge"), module.exports);
29
29
  __reExport(src_exports, require("./image"), module.exports);
30
30
  __reExport(src_exports, require("./locales"), module.exports);
31
+ __reExport(src_exports, require("./arrayUtils"), module.exports);
31
32
  // Annotate the CommonJS export names for ESM import in node:
32
33
  0 && (module.exports = {
33
34
  ...require("./otherUtils"),
@@ -41,5 +42,6 @@ __reExport(src_exports, require("./locales"), module.exports);
41
42
  ...require("./miniRedux"),
42
43
  ...require("./jsBridge"),
43
44
  ...require("./image"),
44
- ...require("./locales")
45
+ ...require("./locales"),
46
+ ...require("./arrayUtils")
45
47
  });
@@ -11,6 +11,6 @@ export declare const miniRedux: <State extends Record<string, any>, Namespace ex
11
11
  payload: any;
12
12
  }) => void;
13
13
  }>;
14
- Provider: (ComponentUi: any) => (props: any) => any;
14
+ Provider: (ComponentUi: any) => any;
15
15
  };
16
16
  export {};
package/lib/miniRedux.js CHANGED
@@ -41,7 +41,7 @@ var miniRedux = ({
41
41
  }) => {
42
42
  const Context = (0, import_react.createContext)({});
43
43
  const Provider = (ComponentUi) => {
44
- const Components = (props) => {
44
+ const Components = (0, import_react.forwardRef)((props, ref) => {
45
45
  const [providerState, dispatch] = (0, import_react.useReducer)(
46
46
  (state2, { type, payload }) => {
47
47
  if (reducers[type]) {
@@ -74,9 +74,9 @@ var miniRedux = ({
74
74
  {
75
75
  value: { [namespace]: providerState, dispatch: _dispatch }
76
76
  },
77
- /* @__PURE__ */ import_react.default.createElement(ComponentUi, { ..._props, ref: _ref })
77
+ /* @__PURE__ */ import_react.default.createElement(ComponentUi, { ..._props, ref })
78
78
  );
79
- };
79
+ });
80
80
  return Components;
81
81
  };
82
82
  return {
@@ -27,7 +27,7 @@ export declare const changeArray: <T>(list: T[] | undefined, item: T, key?: stri
27
27
  * @Date: 2023-12-19 16:54
28
28
  */
29
29
  export declare const getItemByArray: <T>(list: T[] | undefined, item: T, key?: string) => boolean;
30
- export declare const createArray: (length: number, returnItem: any) => any;
30
+ export declare const createArray: (length: number, returnItem: any) => unknown[];
31
31
  /**
32
32
  * 根据对象内容生成唯一id
33
33
  * @param obj
package/lib/platform.d.ts CHANGED
@@ -2,3 +2,8 @@ export declare const isIpad: () => boolean;
2
2
  export declare const isMobile: () => boolean;
3
3
  export declare const isAndroid: () => boolean;
4
4
  export declare const isIos: () => boolean;
5
+ export declare const checkEnv: () => number;
6
+ export declare const isWx: () => boolean;
7
+ export declare const isIOS: () => boolean;
8
+ export declare const isWxApp: () => boolean;
9
+ export declare const isSafari: () => boolean;
package/lib/platform.js CHANGED
@@ -19,17 +19,23 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  // src/platform.ts
20
20
  var platform_exports = {};
21
21
  __export(platform_exports, {
22
+ checkEnv: () => checkEnv,
22
23
  isAndroid: () => isAndroid,
24
+ isIOS: () => isIOS,
23
25
  isIos: () => isIos,
24
26
  isIpad: () => isIpad,
25
- isMobile: () => isMobile
27
+ isMobile: () => isMobile,
28
+ isSafari: () => isSafari,
29
+ isWx: () => isWx,
30
+ isWxApp: () => isWxApp
26
31
  });
27
32
  module.exports = __toCommonJS(platform_exports);
33
+ var isBrowser = typeof window != "undefined" && window.document;
28
34
  var isIpad = () => {
29
35
  var ua = navigator.userAgent;
30
- var isSafari = ua.indexOf("Safari") != -1 && ua.indexOf("Version") != -1;
36
+ var isSafari2 = ua.indexOf("Safari") != -1 && ua.indexOf("Version") != -1;
31
37
  var isIphone = ua.indexOf("iPhone") != -1 && ua.indexOf("Version") != -1;
32
- var isIPad = isSafari && !isIphone && "ontouchend" in document;
38
+ var isIPad = isSafari2 && !isIphone && "ontouchend" in document;
33
39
  if (!/iphone|ios|ipad|android|mobile/i.test(
34
40
  navigator.userAgent.toLowerCase()
35
41
  ) && !isIPad) {
@@ -59,10 +65,68 @@ var isAndroid = () => {
59
65
  var isIos = () => {
60
66
  return /iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase());
61
67
  };
68
+ var checkEnv = () => {
69
+ let env = 0;
70
+ let userAgent = window.navigator.userAgent;
71
+ let isOpera = userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1;
72
+ let isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1;
73
+ let isIE11 = userAgent.indexOf("compatible") === -1 && userAgent.indexOf("Trident") > -1;
74
+ let isEdge = userAgent.indexOf("Edge") > -1;
75
+ let isFF = userAgent.indexOf("Firefox") > -1;
76
+ let isSafari2 = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") === -1;
77
+ let isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("; Win") > -1 && userAgent.indexOf("Safari") > -1;
78
+ if (isOpera || isIE || isIE11 || isEdge || isFF || isSafari2 || isChrome) {
79
+ env = 0;
80
+ } else {
81
+ env = 1;
82
+ }
83
+ return env;
84
+ };
85
+ var isWx = () => {
86
+ if (isBrowser) {
87
+ let ua = "";
88
+ if (isBrowser) {
89
+ ua = window.navigator.userAgent.toLowerCase();
90
+ }
91
+ if (ua.match(/MicroMessenger/i) == "micromessenger") {
92
+ return true;
93
+ }
94
+ return false;
95
+ }
96
+ return false;
97
+ };
98
+ var isIOS = () => {
99
+ if (isBrowser) {
100
+ let u = navigator.userAgent;
101
+ let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
102
+ return isiOS;
103
+ }
104
+ return false;
105
+ };
106
+ var isWxApp = () => {
107
+ if (isBrowser) {
108
+ let u = navigator.userAgent;
109
+ let isWxapp = u.indexOf("miniProgram") !== -1;
110
+ return isWxapp;
111
+ }
112
+ return false;
113
+ };
114
+ var isSafari = () => {
115
+ if (isBrowser) {
116
+ let userAgent = window.navigator.userAgent;
117
+ return userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") === -1 && userAgent.indexOf("CriOS") === -1 && userAgent.indexOf("ChannelName/Feishu") === -1;
118
+ }
119
+ return false;
120
+ };
62
121
  // Annotate the CommonJS export names for ESM import in node:
63
122
  0 && (module.exports = {
123
+ checkEnv,
64
124
  isAndroid,
125
+ isIOS,
65
126
  isIos,
66
127
  isIpad,
67
- isMobile
128
+ isMobile,
129
+ isSafari,
130
+ isWx,
131
+ isWxApp
68
132
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pisell/utils",
3
- "version": "1.0.28",
3
+ "version": "1.0.30",
4
4
  "sideEffects": false,
5
5
  "main": "./lib/index.js",
6
6
  "module": "./es/index.js",