index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. * 格式化科目缩写
  18. */
  19. export function formatSubject(cellValue) {
  20. if (cellValue == null || cellValue == '') return ''
  21. switch (cellValue) {
  22. case '物':
  23. return '物理'
  24. case '历':
  25. return '历史'
  26. case '化':
  27. return '化学'
  28. case '地':
  29. return '地理'
  30. case '政':
  31. return '政治'
  32. case '生':
  33. return '生物'
  34. }
  35. }
  36. /**
  37. * @param {number} time
  38. * @param {string} option
  39. * @returns {string}
  40. */
  41. export function formatTime(time, option) {
  42. if (('' + time).length === 10) {
  43. time = parseInt(time) * 1000
  44. } else {
  45. time = +time
  46. }
  47. const d = new Date(time)
  48. const now = Date.now()
  49. const diff = (now - d) / 1000
  50. if (diff < 30) {
  51. return '刚刚'
  52. } else if (diff < 3600) {
  53. // less 1 hour
  54. return Math.ceil(diff / 60) + '分钟前'
  55. } else if (diff < 3600 * 24) {
  56. return Math.ceil(diff / 3600) + '小时前'
  57. } else if (diff < 3600 * 24 * 2) {
  58. return '1天前'
  59. }
  60. if (option) {
  61. return parseTime(time, option)
  62. } else {
  63. return (
  64. d.getMonth() +
  65. 1 +
  66. '月' +
  67. d.getDate() +
  68. '日' +
  69. d.getHours() +
  70. '时' +
  71. d.getMinutes() +
  72. '分'
  73. )
  74. }
  75. }
  76. /**
  77. * @param {string} url
  78. * @returns {Object}
  79. */
  80. export function getQueryObject(url) {
  81. url = url == null ? window.location.href : url
  82. const search = url.substring(url.lastIndexOf('?') + 1)
  83. const obj = {}
  84. const reg = /([^?&=]+)=([^?&=]*)/g
  85. search.replace(reg, (rs, $1, $2) => {
  86. const name = decodeURIComponent($1)
  87. let val = decodeURIComponent($2)
  88. val = String(val)
  89. obj[name] = val
  90. return rs
  91. })
  92. return obj
  93. }
  94. /**
  95. * @param {string} input value
  96. * @returns {number} output value
  97. */
  98. export function byteLength(str) {
  99. // returns the byte length of an utf8 string
  100. let s = str.length
  101. for (var i = str.length - 1; i >= 0; i--) {
  102. const code = str.charCodeAt(i)
  103. if (code > 0x7f && code <= 0x7ff) {
  104. s++
  105. } else if (code > 0x7ff && code <= 0xffff) s += 2
  106. if (code >= 0xDC00 && code <= 0xDFFF) i--
  107. }
  108. return s
  109. }
  110. /**
  111. * @param {Array} actual
  112. * @returns {Array}
  113. */
  114. export function cleanArray(actual) {
  115. const newArray = []
  116. for (let i = 0; i < actual.length; i++) {
  117. if (actual[i]) {
  118. newArray.push(actual[i])
  119. }
  120. }
  121. return newArray
  122. }
  123. /**
  124. * @param {Object} json
  125. * @returns {Array}
  126. */
  127. export function param(json) {
  128. if (!json) return ''
  129. return cleanArray(
  130. Object.keys(json).map(key => {
  131. if (json[key] === undefined) return ''
  132. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  133. })
  134. ).join('&')
  135. }
  136. /**
  137. * @param {string} url
  138. * @returns {Object}
  139. */
  140. export function param2Obj(url) {
  141. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  142. if (!search) {
  143. return {}
  144. }
  145. const obj = {}
  146. const searchArr = search.split('&')
  147. searchArr.forEach(v => {
  148. const index = v.indexOf('=')
  149. if (index !== -1) {
  150. const name = v.substring(0, index)
  151. const val = v.substring(index + 1, v.length)
  152. obj[name] = val
  153. }
  154. })
  155. return obj
  156. }
  157. /**
  158. * @param {string} val
  159. * @returns {string}
  160. */
  161. export function html2Text(val) {
  162. const div = document.createElement('div')
  163. div.innerHTML = val
  164. return div.textContent || div.innerText
  165. }
  166. /**
  167. * Merges two objects, giving the last one precedence
  168. * @param {Object} target
  169. * @param {(Object|Array)} source
  170. * @returns {Object}
  171. */
  172. export function objectMerge(target, source) {
  173. if (typeof target !== 'object') {
  174. target = {}
  175. }
  176. if (Array.isArray(source)) {
  177. return source.slice()
  178. }
  179. Object.keys(source).forEach(property => {
  180. const sourceProperty = source[property]
  181. if (typeof sourceProperty === 'object') {
  182. target[property] = objectMerge(target[property], sourceProperty)
  183. } else {
  184. target[property] = sourceProperty
  185. }
  186. })
  187. return target
  188. }
  189. /**
  190. * @param {HTMLElement} element
  191. * @param {string} className
  192. */
  193. export function toggleClass(element, className) {
  194. if (!element || !className) {
  195. return
  196. }
  197. let classString = element.className
  198. const nameIndex = classString.indexOf(className)
  199. if (nameIndex === -1) {
  200. classString += '' + className
  201. } else {
  202. classString =
  203. classString.substr(0, nameIndex) +
  204. 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
  326. ? val => map[val.toLowerCase()]
  327. : val => map[val]
  328. }
  329. export const exportDefault = 'export default '
  330. export const beautifierConf = {
  331. html: {
  332. indent_size: '2',
  333. indent_char: ' ',
  334. max_preserve_newlines: '-1',
  335. preserve_newlines: false,
  336. keep_array_indentation: false,
  337. break_chained_methods: false,
  338. indent_scripts: 'separate',
  339. brace_style: 'end-expand',
  340. space_before_conditional: true,
  341. unescape_strings: false,
  342. jslint_happy: false,
  343. end_with_newline: true,
  344. wrap_line_length: '110',
  345. indent_inner_html: true,
  346. comma_first: false,
  347. e4x: true,
  348. indent_empty_lines: true
  349. },
  350. js: {
  351. indent_size: '2',
  352. indent_char: ' ',
  353. max_preserve_newlines: '-1',
  354. preserve_newlines: false,
  355. keep_array_indentation: false,
  356. break_chained_methods: false,
  357. indent_scripts: 'normal',
  358. brace_style: 'end-expand',
  359. space_before_conditional: true,
  360. unescape_strings: false,
  361. jslint_happy: true,
  362. end_with_newline: true,
  363. wrap_line_length: '110',
  364. indent_inner_html: true,
  365. comma_first: false,
  366. e4x: true,
  367. indent_empty_lines: true
  368. }
  369. }
  370. // 首字母大小
  371. export function titleCase(str) {
  372. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  373. }
  374. // 下划转驼峰
  375. export function camelCase(str) {
  376. return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  377. }
  378. export function isNumberStr(str) {
  379. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  380. }
  381. // 取当前月份
  382. export function getDefaultDateRange(delta = 3) {
  383. let date = new Date();
  384. let end = formatShortDate(date)
  385. date = addDays(date, -30 * delta) // 默认取前3个月左右的数据
  386. let beg = formatShortDate(date)
  387. if (!beg.endsWith('01'))
  388. beg = beg.substring(0, beg.length - 2) + '01'
  389. return [beg, end]; //将值设置给插件绑定的数据
  390. }
  391. export function getDefaultSelectRange(days = 15) {
  392. let date = new Date();
  393. let beg = formatShortDate(date)
  394. date = addDays(date, days)
  395. let end = formatShortDate(date)
  396. return [beg, end]
  397. }
  398. export function addDays(date, days) {
  399. if (!date) return date
  400. let time = date.getTime()
  401. time = time + (days * 24 * 3600 * 1000)
  402. return new Date(time)
  403. }
  404. export function formatShortDate(date) {
  405. if (!date) return date
  406. var year = date.getFullYear()
  407. var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  408. var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  409. return year + '-' + month + '-' + day
  410. }
  411. export function formatDuration(totalSeconds, short = true) {
  412. if (!totalSeconds || totalSeconds <= 0) return '0分0秒'
  413. let month = Math.floor(totalSeconds / (3600 * 24 * 30))
  414. let monthRemainder = Math.floor(totalSeconds % (3600 * 24 * 30))
  415. let day = Math.floor(monthRemainder / (3600 * 24))
  416. let dayRemainder = Math.floor(monthRemainder % (3600 * 24))
  417. let hours = Math.floor(dayRemainder / 3600)
  418. let hoursRemainder = Math.floor(dayRemainder % 3600)
  419. let minutes = Math.floor(hoursRemainder / 60)
  420. let minutesRemainder = Math.floor(dayRemainder % 3600)
  421. let seconds = Math.floor(minutesRemainder % 60)
  422. if (short && month == 0 && day == 0) {
  423. let mStr = minutes.toString()
  424. if (mStr.length == 1) mStr = '0' + mStr
  425. let sStr = seconds.toString()
  426. if (sStr.length == 1) sStr = '0' + sStr
  427. return mStr + '分' + sStr + '秒'
  428. }
  429. if (month == 0) {
  430. if (day == 0) {
  431. return hours + '小时' + minutes + '分' + seconds + '秒'
  432. } else {
  433. return day + '天' + hours + '小时' + minutes + '分' + seconds + '秒'
  434. }
  435. } else {
  436. return month + '月' + day + '天' + hours + '小时' + minutes + '分' + seconds + '秒'
  437. }
  438. }
  439. export function createInjectDefaultClosure(defVal) {
  440. return {
  441. default: function() {
  442. return () => defVal
  443. }
  444. }
  445. }