index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import { UUID } from 'uuidjs';
  2. import { parseTime } from './ruoyi';
  3. export function dateFormat(date, format = 'yyyy-MM-dd HH:mm:ss') {
  4. const o = {
  5. 'M+': date.getMonth() + 1, // 月份
  6. 'd+': date.getDate(), // 日
  7. 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
  8. 'H+': date.getHours(), // 小时
  9. 'm+': date.getMinutes(), // 分
  10. 's+': date.getSeconds(), // 秒
  11. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  12. S: date.getMilliseconds(), // 毫秒
  13. a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
  14. A: date.getHours() < 12 ? 'AM' : 'PM' // AM/PM
  15. };
  16. if (/(y+)/.test(format)) {
  17. format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  18. }
  19. for (let k in o) {
  20. if (new RegExp('(' + k + ')').test(format)) {
  21. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  22. }
  23. }
  24. return format;
  25. }
  26. /**
  27. * @description: 获取n天前指定日期
  28. * @param {*} n
  29. */
  30. export const getDayAgoDate = (n = 0) => {
  31. let curDate = new Date();
  32. let newDate = new Date(curDate - 1000 * 60 * 60 * 24 * n);
  33. return newDate
  34. }
  35. /**
  36. * 表格时间格式化
  37. */
  38. export function formatDate(cellValue) {
  39. if (cellValue == null || cellValue == '') return '';
  40. var date = new Date(cellValue);
  41. var year = date.getFullYear();
  42. var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
  43. var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  44. var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  45. var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  46. var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  47. return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  48. }
  49. /**
  50. * @param {number} time
  51. * @param {string} option
  52. * @returns {string}
  53. */
  54. export function formatTime(time, option) {
  55. if (('' + time).length === 10) {
  56. time = parseInt(time) * 1000;
  57. } else {
  58. time = +time;
  59. }
  60. const d = new Date(time);
  61. const now = Date.now();
  62. const diff = (now - d) / 1000;
  63. if (diff < 30) {
  64. return '刚刚';
  65. } else if (diff < 3600) {
  66. // less 1 hour
  67. return Math.ceil(diff / 60) + '分钟前';
  68. } else if (diff < 3600 * 24) {
  69. return Math.ceil(diff / 3600) + '小时前';
  70. } else if (diff < 3600 * 24 * 2) {
  71. return '1天前';
  72. }
  73. if (option) {
  74. return parseTime(time, option);
  75. } else {
  76. return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
  77. }
  78. }
  79. /**
  80. * @param {string} url
  81. * @returns {Object}
  82. */
  83. export function getQueryObject(url) {
  84. url = url == null ? window.location.href : url;
  85. const search = url.substring(url.lastIndexOf('?') + 1);
  86. const obj = {};
  87. const reg = /([^?&=]+)=([^?&=]*)/g;
  88. search.replace(reg, (rs, $1, $2) => {
  89. const name = decodeURIComponent($1);
  90. let val = decodeURIComponent($2);
  91. val = String(val);
  92. obj[name] = val;
  93. return rs;
  94. });
  95. return obj;
  96. }
  97. /**
  98. * @param {string} input value
  99. * @returns {number} output value
  100. */
  101. export function byteLength(str) {
  102. // returns the byte length of an utf8 string
  103. let s = str.length;
  104. for (var i = str.length - 1; i >= 0; i--) {
  105. const code = str.charCodeAt(i);
  106. if (code > 0x7f && code <= 0x7ff) s++;
  107. else if (code > 0x7ff && code <= 0xffff) s += 2;
  108. if (code >= 0xdc00 && code <= 0xdfff) i--;
  109. }
  110. return s;
  111. }
  112. /**
  113. * @param {Array} actual
  114. * @returns {Array}
  115. */
  116. export function cleanArray(actual) {
  117. const newArray = [];
  118. for (let i = 0; i < actual.length; i++) {
  119. if (actual[i]) {
  120. newArray.push(actual[i]);
  121. }
  122. }
  123. return newArray;
  124. }
  125. /**
  126. * @param {Object} json
  127. * @returns {Array}
  128. */
  129. export function param(json) {
  130. if (!json) return '';
  131. return cleanArray(
  132. Object.keys(json).map(key => {
  133. if (json[key] === undefined) return '';
  134. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
  135. })
  136. ).join('&');
  137. }
  138. /**
  139. * @param {string} url
  140. * @returns {Object}
  141. */
  142. export function param2Obj(url) {
  143. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ');
  144. if (!search) {
  145. return {};
  146. }
  147. const obj = {};
  148. const searchArr = search.split('&');
  149. searchArr.forEach(v => {
  150. const index = v.indexOf('=');
  151. if (index !== -1) {
  152. const name = v.substring(0, index);
  153. const val = v.substring(index + 1, v.length);
  154. obj[name] = val;
  155. }
  156. });
  157. return obj;
  158. }
  159. /**
  160. * @param {string} val
  161. * @returns {string}
  162. */
  163. export function html2Text(val) {
  164. const div = document.createElement('div');
  165. div.innerHTML = val;
  166. return div.textContent || div.innerText;
  167. }
  168. /**
  169. * Merges two objects, giving the last one precedence
  170. * @param {Object} target
  171. * @param {(Object|Array)} source
  172. * @returns {Object}
  173. */
  174. export function objectMerge(target, source) {
  175. if (typeof target !== 'object') {
  176. target = {};
  177. }
  178. if (Array.isArray(source)) {
  179. return source.slice();
  180. }
  181. Object.keys(source).forEach(property => {
  182. const sourceProperty = source[property];
  183. if (typeof sourceProperty === 'object') {
  184. target[property] = objectMerge(target[property], sourceProperty);
  185. } else {
  186. target[property] = sourceProperty;
  187. }
  188. });
  189. return target;
  190. }
  191. /**
  192. * @param {HTMLElement} element
  193. * @param {string} className
  194. */
  195. export function toggleClass(element, className) {
  196. if (!element || !className) {
  197. return;
  198. }
  199. let classString = element.className;
  200. const nameIndex = classString.indexOf(className);
  201. if (nameIndex === -1) {
  202. classString += '' + className;
  203. } else {
  204. classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length);
  205. }
  206. element.className = classString;
  207. }
  208. /**
  209. * @param {string} type
  210. * @returns {Date}
  211. */
  212. export function getTime(type) {
  213. if (type === 'start') {
  214. return new Date().getTime() - 3600 * 1000 * 24 * 90;
  215. } else {
  216. return new Date(new Date().toDateString());
  217. }
  218. }
  219. /**
  220. * @param {Function} func
  221. * @param {number} wait
  222. * @param {boolean} immediate
  223. * @return {*}
  224. */
  225. export function debounce(func, wait, immediate) {
  226. let timeout, args, context, timestamp, result;
  227. const later = function () {
  228. // 据上一次触发时间间隔
  229. const last = +new Date() - timestamp;
  230. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  231. if (last < wait && last > 0) {
  232. timeout = setTimeout(later, wait - last);
  233. } else {
  234. timeout = null;
  235. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  236. if (!immediate) {
  237. result = func.apply(context, args);
  238. if (!timeout) context = args = null;
  239. }
  240. }
  241. };
  242. return function (...args) {
  243. context = this;
  244. timestamp = +new Date();
  245. const callNow = immediate && !timeout;
  246. // 如果延时不存在,重新设定延时
  247. if (!timeout) timeout = setTimeout(later, wait);
  248. if (callNow) {
  249. result = func.apply(context, args);
  250. context = args = null;
  251. }
  252. return result;
  253. };
  254. }
  255. /**
  256. * This is just a simple version of deep copy
  257. * Has a lot of edge cases bug
  258. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  259. * @param {Object} source
  260. * @returns {Object}
  261. */
  262. export function deepClone(source) {
  263. if (!source && typeof source !== 'object') {
  264. throw new Error('error arguments', 'deepClone');
  265. }
  266. const targetObj = source.constructor === Array ? [] : {};
  267. Object.keys(source).forEach(keys => {
  268. if (source[keys] && typeof source[keys] === 'object') {
  269. targetObj[keys] = deepClone(source[keys]);
  270. } else {
  271. targetObj[keys] = source[keys];
  272. }
  273. });
  274. return targetObj;
  275. }
  276. /**
  277. * @param {Array} arr
  278. * @returns {Array}
  279. */
  280. export function uniqueArr(arr) {
  281. return Array.from(new Set(arr));
  282. }
  283. /**
  284. * @returns {string}
  285. */
  286. export function createUniqueString() {
  287. const timestamp = +new Date() + '';
  288. const randomNum = parseInt((1 + Math.random()) * 65536) + '';
  289. return (+(randomNum + timestamp)).toString(32);
  290. }
  291. /**
  292. * Check if an element has a class
  293. * @param {HTMLElement} elm
  294. * @param {string} cls
  295. * @returns {boolean}
  296. */
  297. export function hasClass(ele, cls) {
  298. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  299. }
  300. /**
  301. * Add class to element
  302. * @param {HTMLElement} elm
  303. * @param {string} cls
  304. */
  305. export function addClass(ele, cls) {
  306. if (!hasClass(ele, cls)) ele.className += ' ' + cls;
  307. }
  308. /**
  309. * Remove class from element
  310. * @param {HTMLElement} elm
  311. * @param {string} cls
  312. */
  313. export function removeClass(ele, cls) {
  314. if (hasClass(ele, cls)) {
  315. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
  316. ele.className = ele.className.replace(reg, ' ');
  317. }
  318. }
  319. export function makeMap(str, expectsLowerCase) {
  320. const map = Object.create(null);
  321. const list = str.split(',');
  322. for (let i = 0; i < list.length; i++) {
  323. map[list[i]] = true;
  324. }
  325. return expectsLowerCase ? val => map[val.toLowerCase()] : val => map[val];
  326. }
  327. export const exportDefault = 'export default ';
  328. export const beautifierConf = {
  329. html: {
  330. indent_size: '2',
  331. indent_char: ' ',
  332. max_preserve_newlines: '-1',
  333. preserve_newlines: false,
  334. keep_array_indentation: false,
  335. break_chained_methods: false,
  336. indent_scripts: 'separate',
  337. brace_style: 'end-expand',
  338. space_before_conditional: true,
  339. unescape_strings: false,
  340. jslint_happy: false,
  341. end_with_newline: true,
  342. wrap_line_length: '110',
  343. indent_inner_html: true,
  344. comma_first: false,
  345. e4x: true,
  346. indent_empty_lines: true
  347. },
  348. js: {
  349. indent_size: '2',
  350. indent_char: ' ',
  351. max_preserve_newlines: '-1',
  352. preserve_newlines: false,
  353. keep_array_indentation: false,
  354. break_chained_methods: false,
  355. indent_scripts: 'normal',
  356. brace_style: 'end-expand',
  357. space_before_conditional: true,
  358. unescape_strings: false,
  359. jslint_happy: true,
  360. end_with_newline: true,
  361. wrap_line_length: '110',
  362. indent_inner_html: true,
  363. comma_first: false,
  364. e4x: true,
  365. indent_empty_lines: true
  366. }
  367. };
  368. // 首字母大小
  369. export function titleCase(str) {
  370. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase());
  371. }
  372. // 下划转驼峰
  373. export function camelCase(str) {
  374. return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase());
  375. }
  376. export function isNumberStr(str) {
  377. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
  378. }
  379. export const uuid = () => {
  380. return UUID.generate();
  381. };
  382. /**
  383. * 对象浅拷贝,防止嵌套对象的引用还是原来的对象
  384. * @param obj
  385. * @returns {any}
  386. */
  387. export const copyObj = obj => {
  388. return JSON.parse(JSON.stringify(obj));
  389. };