index.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. import { parseTime } from '@/utils/ruoyi';
  2. /**
  3. * 表格时间格式化
  4. */
  5. export const formatDate = (cellValue: string) => {
  6. if (cellValue == null || cellValue == '') return '';
  7. const date = new Date(cellValue);
  8. const year = date.getFullYear();
  9. const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
  10. const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  11. const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  12. const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  13. const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  14. return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  15. };
  16. /**
  17. * @param {number} time
  18. * @param {string} option
  19. * @returns {string}
  20. */
  21. export const formatTime = (time: string, option: string) => {
  22. let t: number;
  23. if (('' + time).length === 10) {
  24. t = parseInt(time) * 1000;
  25. } else {
  26. t = +time;
  27. }
  28. const d: any = new Date(t);
  29. const now = Date.now();
  30. const diff = (now - d) / 1000;
  31. if (diff < 30) {
  32. return '刚刚';
  33. } else if (diff < 3600) {
  34. // less 1 hour
  35. return Math.ceil(diff / 60) + '分钟前';
  36. } else if (diff < 3600 * 24) {
  37. return Math.ceil(diff / 3600) + '小时前';
  38. } else if (diff < 3600 * 24 * 2) {
  39. return '1天前';
  40. }
  41. if (option) {
  42. return parseTime(t, option);
  43. } else {
  44. return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
  45. }
  46. };
  47. /**
  48. * @param {string} url
  49. * @returns {Object}
  50. */
  51. export const getQueryObject = (url: string) => {
  52. url = url == null ? window.location.href : url;
  53. const search = url.substring(url.lastIndexOf('?') + 1);
  54. const obj: { [key: string]: string } = {};
  55. const reg = /([^?&=]+)=([^?&=]*)/g;
  56. search.replace(reg, (rs, $1, $2) => {
  57. const name = decodeURIComponent($1);
  58. let val = decodeURIComponent($2);
  59. val = String(val);
  60. obj[name] = val;
  61. return rs;
  62. });
  63. return obj;
  64. };
  65. /**
  66. * @param {string} input value
  67. * @returns {number} output value
  68. */
  69. export const byteLength = (str: string) => {
  70. // returns the byte length of an utf8 string
  71. let s = str.length;
  72. for (let i = str.length - 1; i >= 0; i--) {
  73. const code = str.charCodeAt(i);
  74. if (code > 0x7f && code <= 0x7ff) s++;
  75. else if (code > 0x7ff && code <= 0xffff) s += 2;
  76. if (code >= 0xdc00 && code <= 0xdfff) i--;
  77. }
  78. return s;
  79. };
  80. /**
  81. * @param {Array} actual
  82. * @returns {Array}
  83. */
  84. export const cleanArray = (actual: Array<any>) => {
  85. const newArray: any[] = [];
  86. for (let i = 0; i < actual.length; i++) {
  87. if (actual[i]) {
  88. newArray.push(actual[i]);
  89. }
  90. }
  91. return newArray;
  92. };
  93. /**
  94. * @param {Object} json
  95. * @returns {Array}
  96. */
  97. export const param = (json: any) => {
  98. if (!json) return '';
  99. return cleanArray(
  100. Object.keys(json).map((key) => {
  101. if (json[key] === undefined) return '';
  102. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
  103. })
  104. ).join('&');
  105. };
  106. /**
  107. * @param {string} url
  108. * @returns {Object}
  109. */
  110. export const param2Obj = (url: string) => {
  111. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ');
  112. if (!search) {
  113. return {};
  114. }
  115. const obj: any = {};
  116. const searchArr = search.split('&');
  117. searchArr.forEach((v) => {
  118. const index = v.indexOf('=');
  119. if (index !== -1) {
  120. const name = v.substring(0, index);
  121. const val = v.substring(index + 1, v.length);
  122. obj[name] = val;
  123. }
  124. });
  125. return obj;
  126. };
  127. /**
  128. * @param {string} val
  129. * @returns {string}
  130. */
  131. export const html2Text = (val: string) => {
  132. const div = document.createElement('div');
  133. div.innerHTML = val;
  134. return div.textContent || div.innerText;
  135. };
  136. /**
  137. * Merges two objects, giving the last one precedence
  138. * @param {Object} target
  139. * @param {(Object|Array)} source
  140. * @returns {Object}
  141. */
  142. export const objectMerge = (target: any, source: any | any[]) => {
  143. if (typeof target !== 'object') {
  144. target = {};
  145. }
  146. if (Array.isArray(source)) {
  147. return source.slice();
  148. }
  149. Object.keys(source).forEach((property) => {
  150. const sourceProperty = source[property];
  151. if (typeof sourceProperty === 'object') {
  152. target[property] = objectMerge(target[property], sourceProperty);
  153. } else {
  154. target[property] = sourceProperty;
  155. }
  156. });
  157. return target;
  158. };
  159. /**
  160. * @param {HTMLElement} element
  161. * @param {string} className
  162. */
  163. export const toggleClass = (element: HTMLElement, className: string) => {
  164. if (!element || !className) {
  165. return;
  166. }
  167. let classString = element.className;
  168. const nameIndex = classString.indexOf(className);
  169. if (nameIndex === -1) {
  170. classString += '' + className;
  171. } else {
  172. classString = classString.substring(0, nameIndex) + classString.substring(nameIndex + className.length);
  173. }
  174. element.className = classString;
  175. };
  176. /**
  177. * @param {string} type
  178. * @returns {Date}
  179. */
  180. export const getTime = (type: string) => {
  181. if (type === 'start') {
  182. return new Date().getTime() - 3600 * 1000 * 24 * 90;
  183. } else {
  184. return new Date(new Date().toDateString());
  185. }
  186. };
  187. /**
  188. * @param {Function} func
  189. * @param {number} wait
  190. * @param {boolean} immediate
  191. * @return {*}
  192. */
  193. export const debounce = (func: any, wait: number, immediate: boolean) => {
  194. let timeout: any, args: any, context: any, timestamp: any, result: any;
  195. const later = function () {
  196. // 据上一次触发时间间隔
  197. const last = +new Date() - timestamp;
  198. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  199. if (last < wait && last > 0) {
  200. timeout = setTimeout(later, wait - last);
  201. } else {
  202. timeout = null;
  203. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  204. if (!immediate) {
  205. result = func.apply(context, args);
  206. if (!timeout) context = args = null;
  207. }
  208. }
  209. };
  210. return (...args: any) => {
  211. context = this;
  212. timestamp = +new Date();
  213. const callNow = immediate && !timeout;
  214. // 如果延时不存在,重新设定延时
  215. if (!timeout) timeout = setTimeout(later, wait);
  216. if (callNow) {
  217. result = func.apply(context, args);
  218. context = args = null;
  219. }
  220. return result;
  221. };
  222. };
  223. /**
  224. * This is just a simple version of deep copy
  225. * Has a lot of edge cases bug
  226. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  227. * @param {Object} source
  228. * @returns {Object}
  229. */
  230. export const deepClone = (source: any) => {
  231. if (!source && typeof source !== 'object') {
  232. throw new Error('error arguments', 'deepClone' as any);
  233. }
  234. const targetObj: any = source.constructor === Array ? [] : {};
  235. Object.keys(source).forEach((keys) => {
  236. if (source[keys] && typeof source[keys] === 'object') {
  237. targetObj[keys] = deepClone(source[keys]);
  238. } else {
  239. targetObj[keys] = source[keys];
  240. }
  241. });
  242. return targetObj;
  243. };
  244. /**
  245. * @param {Array} arr
  246. * @returns {Array}
  247. */
  248. export const uniqueArr = (arr: any) => {
  249. return Array.from(new Set(arr));
  250. };
  251. /**
  252. * @returns {string}
  253. */
  254. export const createUniqueString = (): string => {
  255. const timestamp = +new Date() + '';
  256. const num = (1 + Math.random()) * 65536;
  257. const randomNum = parseInt(num + '');
  258. return (+(randomNum + timestamp)).toString(32);
  259. };
  260. /**
  261. * Check if an element has a class
  262. * @param ele
  263. * @param {string} cls
  264. * @returns {boolean}
  265. */
  266. export const hasClass = (ele: HTMLElement, cls: string): boolean => {
  267. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  268. };
  269. /**
  270. * Add class to element
  271. * @param ele
  272. * @param {string} cls
  273. */
  274. export const addClass = (ele: HTMLElement, cls: string) => {
  275. if (!hasClass(ele, cls)) ele.className += ' ' + cls;
  276. };
  277. /**
  278. * Remove class from element
  279. * @param ele
  280. * @param {string} cls
  281. */
  282. export const removeClass = (ele: HTMLElement, cls: string) => {
  283. if (hasClass(ele, cls)) {
  284. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
  285. ele.className = ele.className.replace(reg, ' ');
  286. }
  287. };
  288. /**
  289. * @param {string} path
  290. * @returns {Boolean}
  291. */
  292. export const isExternal = (path: string) => {
  293. return /^(https?:|http?:|mailto:|tel:)/.test(path);
  294. };