index.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. * @param {Array} arr
  257. * @returns {Array}
  258. */
  259. export function uniqueArr(arr) {
  260. return Array.from(new Set(arr))
  261. }
  262. /**
  263. * @returns {string}
  264. */
  265. export function createUniqueString() {
  266. const timestamp = +new Date() + ''
  267. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  268. return (+(randomNum + timestamp)).toString(32)
  269. }
  270. /**
  271. * Check if an element has a class
  272. * @param {HTMLElement} elm
  273. * @param {string} cls
  274. * @returns {boolean}
  275. */
  276. export function hasClass(ele, cls) {
  277. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  278. }
  279. /**
  280. * Add class to element
  281. * @param {HTMLElement} elm
  282. * @param {string} cls
  283. */
  284. export function addClass(ele, cls) {
  285. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  286. }
  287. /**
  288. * Remove class from element
  289. * @param {HTMLElement} elm
  290. * @param {string} cls
  291. */
  292. export function removeClass(ele, cls) {
  293. if (hasClass(ele, cls)) {
  294. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  295. ele.className = ele.className.replace(reg, ' ')
  296. }
  297. }
  298. export function makeMap(str, expectsLowerCase) {
  299. const map = Object.create(null)
  300. const list = str.split(',')
  301. for (let i = 0; i < list.length; i++) {
  302. map[list[i]] = true
  303. }
  304. return expectsLowerCase
  305. ? val => map[val.toLowerCase()]
  306. : val => map[val]
  307. }
  308. export const exportDefault = 'export default '
  309. export const beautifierConf = {
  310. html: {
  311. indent_size: '2',
  312. indent_char: ' ',
  313. max_preserve_newlines: '-1',
  314. preserve_newlines: false,
  315. keep_array_indentation: false,
  316. break_chained_methods: false,
  317. indent_scripts: 'separate',
  318. brace_style: 'end-expand',
  319. space_before_conditional: true,
  320. unescape_strings: false,
  321. jslint_happy: false,
  322. end_with_newline: true,
  323. wrap_line_length: '110',
  324. indent_inner_html: true,
  325. comma_first: false,
  326. e4x: true,
  327. indent_empty_lines: true
  328. },
  329. js: {
  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: 'normal',
  337. brace_style: 'end-expand',
  338. space_before_conditional: true,
  339. unescape_strings: false,
  340. jslint_happy: true,
  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. }
  349. // 首字母大小
  350. export function titleCase(str) {
  351. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  352. }
  353. // 下划转驼峰
  354. export function camelCase(str) {
  355. return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  356. }
  357. export function isNumberStr(str) {
  358. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  359. }