index.js 11 KB

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