You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

441 regels
10 KiB

  1. import { parseTime } from './ruoyi'
  2. /**
  3. * 表格时间格式化
  4. */
  5. export function formatDate(cellValue) {
  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 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 str
  76. * @param str
  77. */
  78. export function byteLength(str) {
  79. // returns the byte length of an utf8 string
  80. let s = str.length
  81. for (let 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. obj[name] = v.substring(index + 1, v.length)
  131. }
  132. })
  133. return obj
  134. }
  135. /**
  136. * @param {string} val
  137. * @returns {string}
  138. */
  139. export function html2Text(val) {
  140. const div = document.createElement('div')
  141. div.innerHTML = val
  142. return div.textContent || div.innerText
  143. }
  144. /**
  145. * Merges two objects, giving the last one precedence
  146. * @param {Object} target
  147. * @param {(Object|Array)} source
  148. * @returns {Object}
  149. */
  150. export function objectMerge(target, source) {
  151. if (typeof target !== 'object') {
  152. target = {}
  153. }
  154. if (Array.isArray(source)) {
  155. return source.slice()
  156. }
  157. Object.keys(source).forEach(property => {
  158. const sourceProperty = source[property]
  159. if (typeof sourceProperty === 'object') {
  160. target[property] = objectMerge(target[property], sourceProperty)
  161. } else {
  162. target[property] = sourceProperty
  163. }
  164. })
  165. return target
  166. }
  167. /**
  168. * @param {HTMLElement} element
  169. * @param {string} className
  170. */
  171. export function toggleClass(element, className) {
  172. if (!element || !className) {
  173. return
  174. }
  175. let classString = element.className
  176. const nameIndex = classString.indexOf(className)
  177. if (nameIndex === -1) {
  178. classString += '' + className
  179. } else {
  180. classString =
  181. classString.substr(0, nameIndex) +
  182. classString.substr(nameIndex + className.length)
  183. }
  184. element.className = classString
  185. }
  186. /**
  187. * @param {string} type
  188. * @returns {Date}
  189. */
  190. export function getTime(type) {
  191. if (type === 'start') {
  192. return new Date().getTime() - 3600 * 1000 * 24 * 90
  193. } else {
  194. return new Date(new Date().toDateString())
  195. }
  196. }
  197. /**
  198. * @param {Function} func
  199. * @param {number} wait
  200. * @param {boolean} immediate
  201. * @return {*}
  202. */
  203. export function debounce(func, wait, immediate) {
  204. let timeout, args, context, timestamp, result
  205. const later = function() {
  206. // 据上一次触发时间间隔
  207. const last = +new Date() - timestamp
  208. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  209. if (last < wait && last > 0) {
  210. timeout = setTimeout(later, wait - last)
  211. } else {
  212. timeout = null
  213. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  214. if (!immediate) {
  215. result = func.apply(context, args)
  216. if (!timeout) context = args = null
  217. }
  218. }
  219. }
  220. return function(...args) {
  221. context = this
  222. timestamp = +new Date()
  223. const callNow = immediate && !timeout
  224. // 如果延时不存在,重新设定延时
  225. if (!timeout) timeout = setTimeout(later, wait)
  226. if (callNow) {
  227. result = func.apply(context, args)
  228. context = args = null
  229. }
  230. return result
  231. }
  232. }
  233. // /**
  234. // * This is just a simple version of deep copy
  235. // * Has a lot of edge cases bug
  236. // * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  237. // * @param {Object} source
  238. // * @returns {Object}
  239. // */
  240. // export function deepClone(source) {
  241. // if (!source && typeof source !== 'object') {
  242. // throw new Error('error arguments', 'deepClone')
  243. // }
  244. // const targetObj = source.constructor === Array ? [] : {}
  245. // Object.keys(source).forEach(keys => {
  246. // if (source[keys] && typeof source[keys] === 'object') {
  247. // targetObj[keys] = deepClone(source[keys])
  248. // } else {
  249. // targetObj[keys] = source[keys]
  250. // }
  251. // })
  252. // return targetObj
  253. // }
  254. // 深拷贝对象
  255. // add by 芋道源码 https://github.com/JakHuang/form-generator/blob/dev/src/utils/index.js#L107
  256. export function deepClone(obj) {
  257. const _toString = Object.prototype.toString
  258. // null, undefined, non-object, function
  259. if (!obj || typeof obj !== 'object') {
  260. return obj
  261. }
  262. // DOM Node
  263. if (obj.nodeType && 'cloneNode' in obj) {
  264. return obj.cloneNode(true)
  265. }
  266. // Date
  267. if (_toString.call(obj) === '[object Date]') {
  268. return new Date(obj.getTime())
  269. }
  270. // RegExp
  271. if (_toString.call(obj) === '[object RegExp]') {
  272. const flags = []
  273. if (obj.global) { flags.push('g') }
  274. if (obj.multiline) { flags.push('m') }
  275. if (obj.ignoreCase) { flags.push('i') }
  276. return new RegExp(obj.source, flags.join(''))
  277. }
  278. const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}
  279. for (const key in obj) {
  280. result[key] = deepClone(obj[key])
  281. }
  282. return result
  283. }
  284. /**
  285. * @param {Array} arr
  286. * @returns {Array}
  287. */
  288. export function uniqueArr(arr) {
  289. return Array.from(new Set(arr))
  290. }
  291. /**
  292. * @returns {string}
  293. */
  294. export function createUniqueString() {
  295. const timestamp = +new Date() + ''
  296. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  297. return (+(randomNum + timestamp)).toString(32)
  298. }
  299. /**
  300. * Check if an element has a class
  301. * @param ele
  302. * @param {string} cls
  303. * @returns {boolean}
  304. */
  305. export function hasClass(ele, cls) {
  306. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  307. }
  308. /**
  309. * Add class to element
  310. * @param ele
  311. * @param {string} cls
  312. */
  313. export function addClass(ele, cls) {
  314. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  315. }
  316. /**
  317. * Remove class from element
  318. * @param ele
  319. * @param {string} cls
  320. */
  321. export function removeClass(ele, cls) {
  322. if (hasClass(ele, cls)) {
  323. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  324. ele.className = ele.className.replace(reg, ' ')
  325. }
  326. }
  327. export function makeMap(str, expectsLowerCase) {
  328. const map = Object.create(null)
  329. const list = str.split(',')
  330. for (let i = 0; i < list.length; i++) {
  331. map[list[i]] = true
  332. }
  333. return expectsLowerCase
  334. ? val => map[val.toLowerCase()]
  335. : val => map[val]
  336. }
  337. export const exportDefault = 'export default '
  338. export const beautifierConf = {
  339. html: {
  340. indent_size: '2',
  341. indent_char: ' ',
  342. max_preserve_newlines: '-1',
  343. preserve_newlines: false,
  344. keep_array_indentation: false,
  345. break_chained_methods: false,
  346. indent_scripts: 'separate',
  347. brace_style: 'end-expand',
  348. space_before_conditional: true,
  349. unescape_strings: false,
  350. jslint_happy: false,
  351. end_with_newline: true,
  352. wrap_line_length: '110',
  353. indent_inner_html: true,
  354. comma_first: false,
  355. e4x: true,
  356. indent_empty_lines: true
  357. },
  358. js: {
  359. indent_size: '2',
  360. indent_char: ' ',
  361. max_preserve_newlines: '-1',
  362. preserve_newlines: false,
  363. keep_array_indentation: false,
  364. break_chained_methods: false,
  365. indent_scripts: 'normal',
  366. brace_style: 'end-expand',
  367. space_before_conditional: true,
  368. unescape_strings: false,
  369. jslint_happy: true,
  370. end_with_newline: true,
  371. wrap_line_length: '110',
  372. indent_inner_html: true,
  373. comma_first: false,
  374. e4x: true,
  375. indent_empty_lines: true
  376. }
  377. }
  378. // 首字母大小
  379. export function titleCase(str) {
  380. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  381. }
  382. // 下划转驼峰
  383. export function camelCase(str) {
  384. return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  385. }
  386. export function isNumberStr(str) {
  387. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  388. }
  389. // -转驼峰
  390. export function toCamelCase(str, upperCaseFirst) {
  391. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  392. return group1.toUpperCase();
  393. });
  394. if (upperCaseFirst && str) {
  395. str = str.charAt(0).toUpperCase() + str.slice(1);
  396. }
  397. return str;
  398. }