index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. // /**
  235. // * This is just a simple version of deep copy
  236. // * Has a lot of edge cases bug
  237. // * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  238. // * @param {Object} source
  239. // * @returns {Object}
  240. // */
  241. // export function deepClone(source) {
  242. // if (!source && typeof source !== 'object') {
  243. // throw new Error('error arguments', 'deepClone')
  244. // }
  245. // const targetObj = source.constructor === Array ? [] : {}
  246. // Object.keys(source).forEach(keys => {
  247. // if (source[keys] && typeof source[keys] === 'object') {
  248. // targetObj[keys] = deepClone(source[keys])
  249. // } else {
  250. // targetObj[keys] = source[keys]
  251. // }
  252. // })
  253. // return targetObj
  254. // }
  255. // 深拷贝对象
  256. // add by 芋道源码 https://github.com/JakHuang/form-generator/blob/dev/src/utils/index.js#L107
  257. export function deepClone(obj) {
  258. const _toString = Object.prototype.toString
  259. // null, undefined, non-object, function
  260. if (!obj || typeof obj !== 'object') {
  261. return obj
  262. }
  263. // DOM Node
  264. if (obj.nodeType && 'cloneNode' in obj) {
  265. return obj.cloneNode(true)
  266. }
  267. // Date
  268. if (_toString.call(obj) === '[object Date]') {
  269. return new Date(obj.getTime())
  270. }
  271. // RegExp
  272. if (_toString.call(obj) === '[object RegExp]') {
  273. const flags = []
  274. if (obj.global) { flags.push('g') }
  275. if (obj.multiline) { flags.push('m') }
  276. if (obj.ignoreCase) { flags.push('i') }
  277. return new RegExp(obj.source, flags.join(''))
  278. }
  279. const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}
  280. for (const key in obj) {
  281. result[key] = deepClone(obj[key])
  282. }
  283. return result
  284. }
  285. /**
  286. * @param {Array} arr
  287. * @returns {Array}
  288. */
  289. export function uniqueArr(arr) {
  290. return Array.from(new Set(arr))
  291. }
  292. /**
  293. * @returns {string}
  294. */
  295. export function createUniqueString() {
  296. const timestamp = +new Date() + ''
  297. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  298. return (+(randomNum + timestamp)).toString(32)
  299. }
  300. /**
  301. * Check if an element has a class
  302. * @param {HTMLElement} elm
  303. * @param {string} cls
  304. * @returns {boolean}
  305. */
  306. export function hasClass(ele, cls) {
  307. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  308. }
  309. /**
  310. * Add class to element
  311. * @param {HTMLElement} elm
  312. * @param {string} cls
  313. */
  314. export function addClass(ele, cls) {
  315. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  316. }
  317. /**
  318. * Remove class from element
  319. * @param {HTMLElement} elm
  320. * @param {string} cls
  321. */
  322. export function removeClass(ele, cls) {
  323. if (hasClass(ele, cls)) {
  324. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  325. ele.className = ele.className.replace(reg, ' ')
  326. }
  327. }
  328. export function makeMap(str, expectsLowerCase) {
  329. const map = Object.create(null)
  330. const list = str.split(',')
  331. for (let i = 0; i < list.length; i++) {
  332. map[list[i]] = true
  333. }
  334. return expectsLowerCase
  335. ? val => map[val.toLowerCase()]
  336. : val => map[val]
  337. }
  338. export const exportDefault = 'export default '
  339. export const beautifierConf = {
  340. html: {
  341. indent_size: '2',
  342. indent_char: ' ',
  343. max_preserve_newlines: '-1',
  344. preserve_newlines: false,
  345. keep_array_indentation: false,
  346. break_chained_methods: false,
  347. indent_scripts: 'separate',
  348. brace_style: 'end-expand',
  349. space_before_conditional: true,
  350. unescape_strings: false,
  351. jslint_happy: false,
  352. end_with_newline: true,
  353. wrap_line_length: '110',
  354. indent_inner_html: true,
  355. comma_first: false,
  356. e4x: true,
  357. indent_empty_lines: true
  358. },
  359. js: {
  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: 'normal',
  367. brace_style: 'end-expand',
  368. space_before_conditional: true,
  369. unescape_strings: false,
  370. jslint_happy: true,
  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. }
  379. // 首字母大小
  380. export function titleCase(str) {
  381. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  382. }
  383. // 下划转驼峰
  384. export function camelCase(str) {
  385. return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  386. }
  387. export function isNumberStr(str) {
  388. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  389. }