index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. "use strict";
  2. const common_vendor = require("../../common/vendor.js");
  3. const sheep_helper_test = require("./test.js");
  4. const sheep_helper_digit = require("./digit.js");
  5. function range(min = 0, max = 0, value = 0) {
  6. return Math.max(min, Math.min(max, Number(value)));
  7. }
  8. function getPx(value, unit = false) {
  9. if (sheep_helper_test.test.number(value)) {
  10. return unit ? `${value}px` : Number(value);
  11. }
  12. if (/(rpx|upx)$/.test(value)) {
  13. return unit ? `${common_vendor.index.upx2px(parseInt(value))}px` : Number(common_vendor.index.upx2px(parseInt(value)));
  14. }
  15. return unit ? `${parseInt(value)}px` : parseInt(value);
  16. }
  17. function sleep(value = 30) {
  18. return new Promise((resolve) => {
  19. setTimeout(() => {
  20. resolve();
  21. }, value);
  22. });
  23. }
  24. function os() {
  25. return common_vendor.index.getSystemInfoSync().platform.toLowerCase();
  26. }
  27. function sys() {
  28. return common_vendor.index.getSystemInfoSync();
  29. }
  30. function random(min, max) {
  31. if (min >= 0 && max > 0 && max >= min) {
  32. const gab = max - min + 1;
  33. return Math.floor(Math.random() * gab + min);
  34. }
  35. return 0;
  36. }
  37. function guid(len = 32, firstU = true, radix = null) {
  38. const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  39. const uuid = [];
  40. radix = radix || chars.length;
  41. if (len) {
  42. for (let i = 0; i < len; i++)
  43. uuid[i] = chars[0 | Math.random() * radix];
  44. } else {
  45. let r;
  46. uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
  47. uuid[14] = "4";
  48. for (let i = 0; i < 36; i++) {
  49. if (!uuid[i]) {
  50. r = 0 | Math.random() * 16;
  51. uuid[i] = chars[i == 19 ? r & 3 | 8 : r];
  52. }
  53. }
  54. }
  55. if (firstU) {
  56. uuid.shift();
  57. return `u${uuid.join("")}`;
  58. }
  59. return uuid.join("");
  60. }
  61. function $parent(name = void 0) {
  62. let parent = this.$parent;
  63. while (parent) {
  64. if (parent.$options && parent.$options.name !== name) {
  65. parent = parent.$parent;
  66. } else {
  67. return parent;
  68. }
  69. }
  70. return false;
  71. }
  72. function addStyle(customStyle, target = "object") {
  73. if (sheep_helper_test.test.empty(customStyle) || typeof customStyle === "object" && target === "object" || target === "string" && typeof customStyle === "string") {
  74. return customStyle;
  75. }
  76. if (target === "object") {
  77. customStyle = trim(customStyle);
  78. const styleArray = customStyle.split(";");
  79. const style = {};
  80. for (let i = 0; i < styleArray.length; i++) {
  81. if (styleArray[i]) {
  82. const item = styleArray[i].split(":");
  83. style[trim(item[0])] = trim(item[1]);
  84. }
  85. }
  86. return style;
  87. }
  88. let string = "";
  89. for (const i in customStyle) {
  90. const key = i.replace(/([A-Z])/g, "-$1").toLowerCase();
  91. string += `${key}:${customStyle[i]};`;
  92. }
  93. return trim(string);
  94. }
  95. function addUnit(value = "auto", unit = "px") {
  96. value = String(value);
  97. return sheep_helper_test.test.number(value) ? `${value}${unit}` : value;
  98. }
  99. function deepClone(obj) {
  100. if ([null, void 0, NaN, false].includes(obj))
  101. return obj;
  102. if (typeof obj !== "object" && typeof obj !== "function") {
  103. return obj;
  104. }
  105. const o = sheep_helper_test.test.array(obj) ? [] : {};
  106. for (const i in obj) {
  107. if (obj.hasOwnProperty(i)) {
  108. o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
  109. }
  110. }
  111. return o;
  112. }
  113. function deepMerge(target = {}, source = {}) {
  114. target = deepClone(target);
  115. if (typeof target !== "object" || typeof source !== "object")
  116. return false;
  117. for (const prop in source) {
  118. if (!source.hasOwnProperty(prop))
  119. continue;
  120. if (prop in target) {
  121. if (typeof target[prop] !== "object") {
  122. target[prop] = source[prop];
  123. } else if (typeof source[prop] !== "object") {
  124. target[prop] = source[prop];
  125. } else if (target[prop].concat && source[prop].concat) {
  126. target[prop] = target[prop].concat(source[prop]);
  127. } else {
  128. target[prop] = deepMerge(target[prop], source[prop]);
  129. }
  130. } else {
  131. target[prop] = source[prop];
  132. }
  133. }
  134. return target;
  135. }
  136. function error(err) {
  137. {
  138. console.error(`SheepJS:${err}`);
  139. }
  140. }
  141. function randomArray(array = []) {
  142. return array.sort(() => Math.random() - 0.5);
  143. }
  144. if (!String.prototype.padStart) {
  145. String.prototype.padStart = function(maxLength, fillString = " ") {
  146. if (Object.prototype.toString.call(fillString) !== "[object String]") {
  147. throw new TypeError("fillString must be String");
  148. }
  149. const str = this;
  150. if (str.length >= maxLength)
  151. return String(str);
  152. const fillLength = maxLength - str.length;
  153. let times = Math.ceil(fillLength / fillString.length);
  154. while (times >>= 1) {
  155. fillString += fillString;
  156. if (times === 1) {
  157. fillString += fillString;
  158. }
  159. }
  160. return fillString.slice(0, fillLength) + str;
  161. };
  162. }
  163. function timeFormat(dateTime = null, formatStr = "yyyy-mm-dd") {
  164. let date;
  165. if (!dateTime) {
  166. date = /* @__PURE__ */ new Date();
  167. } else if (/^\d{10}$/.test(dateTime == null ? void 0 : dateTime.toString().trim())) {
  168. date = new Date(dateTime * 1e3);
  169. } else if (typeof dateTime === "string" && /^\d+$/.test(dateTime.trim())) {
  170. date = new Date(Number(dateTime));
  171. } else {
  172. date = new Date(typeof dateTime === "string" ? dateTime.replace(/-/g, "/") : dateTime);
  173. }
  174. const timeSource = {
  175. y: date.getFullYear().toString(),
  176. // 年
  177. m: (date.getMonth() + 1).toString().padStart(2, "0"),
  178. // 月
  179. d: date.getDate().toString().padStart(2, "0"),
  180. // 日
  181. h: date.getHours().toString().padStart(2, "0"),
  182. // 时
  183. M: date.getMinutes().toString().padStart(2, "0"),
  184. // 分
  185. s: date.getSeconds().toString().padStart(2, "0")
  186. // 秒
  187. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  188. };
  189. for (const key in timeSource) {
  190. const [ret] = new RegExp(`${key}+`).exec(formatStr) || [];
  191. if (ret) {
  192. const beginIndex = key === "y" && ret.length === 2 ? 2 : 0;
  193. formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex));
  194. }
  195. }
  196. return formatStr;
  197. }
  198. function timeFrom(timestamp = null, format = "yyyy-mm-dd") {
  199. if (timestamp == null)
  200. timestamp = Number(/* @__PURE__ */ new Date());
  201. timestamp = parseInt(timestamp);
  202. if (timestamp.toString().length == 10)
  203. timestamp *= 1e3;
  204. let timer = (/* @__PURE__ */ new Date()).getTime() - timestamp;
  205. timer = parseInt(timer / 1e3);
  206. let tips = "";
  207. switch (true) {
  208. case timer < 300:
  209. tips = "刚刚";
  210. break;
  211. case (timer >= 300 && timer < 3600):
  212. tips = `${parseInt(timer / 60)}分钟前`;
  213. break;
  214. case (timer >= 3600 && timer < 86400):
  215. tips = `${parseInt(timer / 3600)}小时前`;
  216. break;
  217. case (timer >= 86400 && timer < 2592e3):
  218. tips = `${parseInt(timer / 86400)}天前`;
  219. break;
  220. default:
  221. if (format === false) {
  222. if (timer >= 2592e3 && timer < 365 * 86400) {
  223. tips = `${parseInt(timer / (86400 * 30))}个月前`;
  224. } else {
  225. tips = `${parseInt(timer / (86400 * 365))}年前`;
  226. }
  227. } else {
  228. tips = timeFormat(timestamp, format);
  229. }
  230. }
  231. return tips;
  232. }
  233. function trim(str, pos = "both") {
  234. str = String(str);
  235. if (pos == "both") {
  236. return str.replace(/^\s+|\s+$/g, "");
  237. }
  238. if (pos == "left") {
  239. return str.replace(/^\s*/, "");
  240. }
  241. if (pos == "right") {
  242. return str.replace(/(\s*$)/g, "");
  243. }
  244. if (pos == "all") {
  245. return str.replace(/\s+/g, "");
  246. }
  247. return str;
  248. }
  249. function queryParams(data = {}, isPrefix = true, arrayFormat = "brackets") {
  250. const prefix = isPrefix ? "?" : "";
  251. const _result = [];
  252. if (["indices", "brackets", "repeat", "comma"].indexOf(arrayFormat) == -1)
  253. arrayFormat = "brackets";
  254. for (const key in data) {
  255. const value = data[key];
  256. if (["", void 0, null].indexOf(value) >= 0) {
  257. continue;
  258. }
  259. if (value.constructor === Array) {
  260. switch (arrayFormat) {
  261. case "indices":
  262. for (let i = 0; i < value.length; i++) {
  263. _result.push(`${key}[${i}]=${value[i]}`);
  264. }
  265. break;
  266. case "brackets":
  267. value.forEach((_value) => {
  268. _result.push(`${key}[]=${_value}`);
  269. });
  270. break;
  271. case "repeat":
  272. value.forEach((_value) => {
  273. _result.push(`${key}=${_value}`);
  274. });
  275. break;
  276. case "comma":
  277. let commaStr = "";
  278. value.forEach((_value) => {
  279. commaStr += (commaStr ? "," : "") + _value;
  280. });
  281. _result.push(`${key}=${commaStr}`);
  282. break;
  283. default:
  284. value.forEach((_value) => {
  285. _result.push(`${key}[]=${_value}`);
  286. });
  287. }
  288. } else {
  289. _result.push(`${key}=${value}`);
  290. }
  291. }
  292. return _result.length ? prefix + _result.join("&") : "";
  293. }
  294. function toast(title, duration = 2e3) {
  295. common_vendor.index.showToast({
  296. title: String(title),
  297. icon: "none",
  298. duration
  299. });
  300. }
  301. function type2icon(type = "success", fill = false) {
  302. if (["primary", "info", "error", "warning", "success"].indexOf(type) == -1)
  303. type = "success";
  304. let iconName = "";
  305. switch (type) {
  306. case "primary":
  307. iconName = "info-circle";
  308. break;
  309. case "info":
  310. iconName = "info-circle";
  311. break;
  312. case "error":
  313. iconName = "close-circle";
  314. break;
  315. case "warning":
  316. iconName = "error-circle";
  317. break;
  318. case "success":
  319. iconName = "checkmark-circle";
  320. break;
  321. default:
  322. iconName = "checkmark-circle";
  323. }
  324. if (fill)
  325. iconName += "-fill";
  326. return iconName;
  327. }
  328. function priceFormat(number, decimals = 0, decimalPoint = ".", thousandsSeparator = ",") {
  329. number = `${number}`.replace(/[^0-9+-Ee.]/g, "");
  330. const n = !isFinite(+number) ? 0 : +number;
  331. const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
  332. const sep = typeof thousandsSeparator === "undefined" ? "," : thousandsSeparator;
  333. const dec = typeof decimalPoint === "undefined" ? "." : decimalPoint;
  334. let s = "";
  335. s = (prec ? sheep_helper_digit.round(n, prec) + "" : `${Math.round(n)}`).split(".");
  336. const re = /(-?\d+)(\d{3})/;
  337. while (re.test(s[0])) {
  338. s[0] = s[0].replace(re, `$1${sep}$2`);
  339. }
  340. if ((s[1] || "").length < prec) {
  341. s[1] = s[1] || "";
  342. s[1] += new Array(prec - s[1].length + 1).join("0");
  343. }
  344. return s.join(dec);
  345. }
  346. function getDuration(value, unit = true) {
  347. const valueNum = parseInt(value);
  348. if (unit) {
  349. if (/s$/.test(value))
  350. return value;
  351. return value > 30 ? `${value}ms` : `${value}s`;
  352. }
  353. if (/ms$/.test(value))
  354. return valueNum;
  355. if (/s$/.test(value))
  356. return valueNum > 30 ? valueNum : valueNum * 1e3;
  357. return valueNum;
  358. }
  359. function padZero(value) {
  360. return `00${value}`.slice(-2);
  361. }
  362. function getProperty(obj, key) {
  363. if (!obj) {
  364. return;
  365. }
  366. if (typeof key !== "string" || key === "") {
  367. return "";
  368. }
  369. if (key.indexOf(".") !== -1) {
  370. const keys = key.split(".");
  371. let firstObj = obj[keys[0]] || {};
  372. for (let i = 1; i < keys.length; i++) {
  373. if (firstObj) {
  374. firstObj = firstObj[keys[i]];
  375. }
  376. }
  377. return firstObj;
  378. }
  379. return obj[key];
  380. }
  381. function setProperty(obj, key, value) {
  382. if (!obj) {
  383. return;
  384. }
  385. const inFn = function(_obj, keys, v) {
  386. if (keys.length === 1) {
  387. _obj[keys[0]] = v;
  388. return;
  389. }
  390. while (keys.length > 1) {
  391. const k = keys[0];
  392. if (!_obj[k] || typeof _obj[k] !== "object") {
  393. _obj[k] = {};
  394. }
  395. keys.shift();
  396. inFn(_obj[k], keys, v);
  397. }
  398. };
  399. if (typeof key !== "string" || key === "")
  400. ;
  401. else if (key.indexOf(".") !== -1) {
  402. const keys = key.split(".");
  403. inFn(obj, keys, value);
  404. } else {
  405. obj[key] = value;
  406. }
  407. }
  408. function page() {
  409. var _a;
  410. const pages2 = getCurrentPages();
  411. return `/${((_a = pages2[pages2.length - 1]) == null ? void 0 : _a.route) ?? ""}`;
  412. }
  413. function pages() {
  414. const pages2 = getCurrentPages();
  415. return pages2;
  416. }
  417. function getRootUrl() {
  418. let url = "";
  419. return url;
  420. }
  421. function copyText(text) {
  422. common_vendor.index.setClipboardData({
  423. data: text,
  424. success: function() {
  425. toast("复制成功!");
  426. },
  427. fail: function() {
  428. toast("复制失败!");
  429. }
  430. });
  431. }
  432. const $helper = {
  433. range,
  434. getPx,
  435. sleep,
  436. os,
  437. sys,
  438. random,
  439. guid,
  440. $parent,
  441. addStyle,
  442. addUnit,
  443. deepClone,
  444. deepMerge,
  445. error,
  446. randomArray,
  447. timeFormat,
  448. timeFrom,
  449. trim,
  450. queryParams,
  451. toast,
  452. type2icon,
  453. priceFormat,
  454. getDuration,
  455. padZero,
  456. getProperty,
  457. setProperty,
  458. page,
  459. pages,
  460. test: sheep_helper_test.test,
  461. getRootUrl,
  462. copyText
  463. };
  464. exports.$helper = $helper;
  465. exports.$parent = $parent;
  466. exports.addStyle = addStyle;
  467. exports.addUnit = addUnit;
  468. exports.deepMerge = deepMerge;
  469. exports.getPx = getPx;
  470. exports.guid = guid;
  471. exports.os = os;
  472. exports.sleep = sleep;
  473. exports.sys = sys;