index.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import { parseTime } from './ruoyi'
  2. // export const $ = name => document.querySelector(name)
  3. // export const getContainerSize = dom => ({ width: dom.getBoundingClientRect().width, height: dom.getBoundingClientRect().height })
  4. // export const getImg = name => require(`../assets/${ name }`)
  5. /**
  6. * 表格时间格式化
  7. */
  8. export function formatDate(cellValue) {
  9. if (cellValue == null || cellValue == "") return "";
  10. var date = new Date(cellValue)
  11. var year = date.getFullYear()
  12. var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  13. var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  14. var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  15. var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  16. var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  17. return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  18. }
  19. /**
  20. * @param {number} time
  21. * @param {string} option
  22. * @returns {string}
  23. */
  24. export function formatTime(time, option) {
  25. if (('' + time).length === 10) {
  26. time = parseInt(time) * 1000
  27. } else {
  28. time = +time
  29. }
  30. const d = new Date(time)
  31. const now = Date.now()
  32. const diff = (now - d) / 1000
  33. if (diff < 30) {
  34. return '刚刚'
  35. } else if (diff < 3600) {
  36. // less 1 hour
  37. return Math.ceil(diff / 60) + '分钟前'
  38. } else if (diff < 3600 * 24) {
  39. return Math.ceil(diff / 3600) + '小时前'
  40. } else if (diff < 3600 * 24 * 2) {
  41. return '1天前'
  42. }
  43. if (option) {
  44. return parseTime(time, option)
  45. } else {
  46. return (
  47. d.getMonth() +
  48. 1 +
  49. '月' +
  50. d.getDate() +
  51. '日' +
  52. d.getHours() +
  53. '时' +
  54. d.getMinutes() +
  55. '分'
  56. )
  57. }
  58. }
  59. /**
  60. * @param {string} url
  61. * @returns {Object}
  62. */
  63. export function getQueryObject(url) {
  64. url = url == null ? window.location.href : url
  65. const search = url.substring(url.lastIndexOf('?') + 1)
  66. const obj = {}
  67. const reg = /([^?&=]+)=([^?&=]*)/g
  68. search.replace(reg, (rs, $1, $2) => {
  69. const name = decodeURIComponent($1)
  70. let val = decodeURIComponent($2)
  71. val = String(val)
  72. obj[name] = val
  73. return rs
  74. })
  75. return obj
  76. }
  77. /**
  78. * @param {string} input value
  79. * @returns {number} output value
  80. */
  81. export function byteLength(str) {
  82. // returns the byte length of an utf8 string
  83. let s = str.length
  84. for (var i = str.length - 1; i >= 0; i--) {
  85. const code = str.charCodeAt(i)
  86. if (code > 0x7f && code <= 0x7ff) s++
  87. else if (code > 0x7ff && code <= 0xffff) s += 2
  88. if (code >= 0xDC00 && code <= 0xDFFF) i--
  89. }
  90. return s
  91. }
  92. /**
  93. * @param {Array} actual
  94. * @returns {Array}
  95. */
  96. export function cleanArray(actual) {
  97. const newArray = []
  98. for (let i = 0; i < actual.length; i++) {
  99. if (actual[i]) {
  100. newArray.push(actual[i])
  101. }
  102. }
  103. return newArray
  104. }
  105. /**
  106. * @param {Object} json
  107. * @returns {Array}
  108. */
  109. export function param(json) {
  110. if (!json) return ''
  111. return cleanArray(
  112. Object.keys(json).map(key => {
  113. if (json[key] === undefined) return ''
  114. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  115. })
  116. ).join('&')
  117. }
  118. /**
  119. * @param {string} url
  120. * @returns {Object}
  121. */
  122. export function param2Obj(url) {
  123. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  124. if (!search) {
  125. return {}
  126. }
  127. const obj = {}
  128. const searchArr = search.split('&')
  129. searchArr.forEach(v => {
  130. const index = v.indexOf('=')
  131. if (index !== -1) {
  132. const name = v.substring(0, index)
  133. const val = v.substring(index + 1, v.length)
  134. obj[name] = val
  135. }
  136. })
  137. return obj
  138. }
  139. /**
  140. * @param {string} val
  141. * @returns {string}
  142. */
  143. export function html2Text(val) {
  144. const div = document.createElement('div')
  145. div.innerHTML = val
  146. return div.textContent || div.innerText
  147. }
  148. /**
  149. * Merges two objects, giving the last one precedence
  150. * @param {Object} target
  151. * @param {(Object|Array)} source
  152. * @returns {Object}
  153. */
  154. export function objectMerge(target, source) {
  155. if (typeof target !== 'object') {
  156. target = {}
  157. }
  158. if (Array.isArray(source)) {
  159. return source.slice()
  160. }
  161. Object.keys(source).forEach(property => {
  162. const sourceProperty = source[property]
  163. if (typeof sourceProperty === 'object') {
  164. target[property] = objectMerge(target[property], sourceProperty)
  165. } else {
  166. target[property] = sourceProperty
  167. }
  168. })
  169. return target
  170. }
  171. /**
  172. * @param {HTMLElement} element
  173. * @param {string} className
  174. */
  175. export function toggleClass(element, className) {
  176. if (!element || !className) {
  177. return
  178. }
  179. let classString = element.className
  180. const nameIndex = classString.indexOf(className)
  181. if (nameIndex === -1) {
  182. classString += '' + className
  183. } else {
  184. classString =
  185. classString.substr(0, nameIndex) +
  186. classString.substr(nameIndex + className.length)
  187. }
  188. element.className = classString
  189. }
  190. /**
  191. * @param {string} type
  192. * @returns {Date}
  193. */
  194. export function getTime(type) {
  195. if (type === 'start') {
  196. return new Date().getTime() - 3600 * 1000 * 24 * 90
  197. } else {
  198. return new Date(new Date().toDateString())
  199. }
  200. }
  201. /**
  202. * @param {Function} func
  203. * @param {number} wait
  204. * @param {boolean} immediate
  205. * @return {*}
  206. */
  207. export function debounce(func, wait, immediate) {
  208. let timeout, args, context, timestamp, result
  209. const later = function () {
  210. // 据上一次触发时间间隔
  211. const last = +new Date() - timestamp
  212. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  213. if (last < wait && last > 0) {
  214. timeout = setTimeout(later, wait - last)
  215. } else {
  216. timeout = null
  217. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  218. if (!immediate) {
  219. result = func.apply(context, args)
  220. if (!timeout) context = args = null
  221. }
  222. }
  223. }
  224. return function (...args) {
  225. context = this
  226. timestamp = +new Date()
  227. const callNow = immediate && !timeout
  228. // 如果延时不存在,重新设定延时
  229. if (!timeout) timeout = setTimeout(later, wait)
  230. if (callNow) {
  231. result = func.apply(context, args)
  232. context = args = null
  233. }
  234. return result
  235. }
  236. }
  237. /**
  238. *
  239. */
  240. export function throttle(fn, delay) {
  241. let timer = null;
  242. return function () {
  243. let context = this;
  244. let args = arguments;
  245. if (!timer) {
  246. timer = setTimeout(function () {
  247. fn.apply(context, args);
  248. timer = null;
  249. }, delay);
  250. }
  251. }
  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. export function deepClone(source) {
  261. if (!source && typeof source !== 'object') {
  262. throw new Error('error arguments', 'deepClone')
  263. }
  264. const targetObj = source.constructor === Array ? [] : {}
  265. Object.keys(source).forEach(keys => {
  266. if (source[keys] && typeof source[keys] === 'object') {
  267. targetObj[keys] = deepClone(source[keys])
  268. } else {
  269. targetObj[keys] = source[keys]
  270. }
  271. })
  272. return targetObj
  273. }
  274. /**
  275. * @param {Array} arr
  276. * @returns {Array}
  277. */
  278. export function uniqueArr(arr) {
  279. return Array.from(new Set(arr))
  280. }
  281. /**
  282. * @returns {string}
  283. */
  284. export function createUniqueString() {
  285. const timestamp = +new Date() + ''
  286. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  287. return (+(randomNum + timestamp)).toString(32)
  288. }
  289. /**
  290. * Check if an element has a class
  291. * @param {HTMLElement} elm
  292. * @param {string} cls
  293. * @returns {boolean}
  294. */
  295. export function hasClass(ele, cls) {
  296. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  297. }
  298. /**
  299. * Add class to element
  300. * @param {HTMLElement} elm
  301. * @param {string} cls
  302. */
  303. export function addClass(ele, cls) {
  304. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  305. }
  306. /**
  307. * Remove class from element
  308. * @param {HTMLElement} elm
  309. * @param {string} cls
  310. */
  311. export function removeClass(ele, cls) {
  312. if (hasClass(ele, cls)) {
  313. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  314. ele.className = ele.className.replace(reg, ' ')
  315. }
  316. }
  317. export function makeMap(str, expectsLowerCase) {
  318. const map = Object.create(null)
  319. const list = str.split(',')
  320. for (let i = 0; i < list.length; i++) {
  321. map[list[i]] = true
  322. }
  323. return expectsLowerCase
  324. ? val => map[val.toLowerCase()]
  325. : val => map[val]
  326. }
  327. export const exportDefault = 'export default '
  328. export const beautifierConf = {
  329. html: {
  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: 'separate',
  337. brace_style: 'end-expand',
  338. space_before_conditional: true,
  339. unescape_strings: false,
  340. jslint_happy: false,
  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. js: {
  349. indent_size: '2',
  350. indent_char: ' ',
  351. max_preserve_newlines: '-1',
  352. preserve_newlines: false,
  353. keep_array_indentation: false,
  354. break_chained_methods: false,
  355. indent_scripts: 'normal',
  356. brace_style: 'end-expand',
  357. space_before_conditional: true,
  358. unescape_strings: false,
  359. jslint_happy: true,
  360. end_with_newline: true,
  361. wrap_line_length: '110',
  362. indent_inner_html: true,
  363. comma_first: false,
  364. e4x: true,
  365. indent_empty_lines: true
  366. }
  367. }
  368. // 首字母大小
  369. export function titleCase(str) {
  370. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  371. }
  372. // 下划转驼峰
  373. export function camelCase(str = '') {
  374. return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  375. }
  376. export function isNumberStr(str) {
  377. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  378. }
  379. // 驼峰转下划线
  380. export function toUnderline(str = '') {
  381. return str.replace(/([A-Z])/g, '_$1').toLowerCase()
  382. }
  383. export const $ = name => document.querySelector(name)
  384. export const getContainerSize = dom => ({ width: dom.getBoundingClientRect().width, height: dom.getBoundingClientRect().height })